<commit_before>#ifndef DUNE_COMMON_COLOR_HH
#define DUNE_COMMON_COLOR_HH

#include <sstream>
#include <assert.h>
#include <iostream>

#ifdef __GNUC__
 #include <cxxabi.h>
#endif
#include <string>

#include <dune/stuff/common/string.hh>

namespace Dune {
namespace Stuff {
namespace Common {

/**
 * @brief namespace to define color constants that can be
 * used to print colored text in an output stream.
 *
 * * \todo this could go into libdune-stuff
 * @warning Some color codes might be unsupported by your terminal.
 */
struct Colors {

#define DS_CONST_CHAR const constexpr char*

// foreground colors
static DS_CONST_CHAR black = "\033[30m";
static DS_CONST_CHAR red = "\033[31m";
static DS_CONST_CHAR green = "\033[32m";
static DS_CONST_CHAR brown = "\033[33m";
static DS_CONST_CHAR blue = "\033[34m";
static DS_CONST_CHAR purple = "\033[35m";
static DS_CONST_CHAR cyan = "\033[36m";
static DS_CONST_CHAR lightgray = "\033[37m";
// light foreground colors
static DS_CONST_CHAR darkgray = "\033[1;30m";
static DS_CONST_CHAR lightred = "\033[1;31m";
static DS_CONST_CHAR lightgreen = "\033[1;32m";
static DS_CONST_CHAR yellow = "\033[1;33m";
static DS_CONST_CHAR lightblue = "\033[1;34m";
static DS_CONST_CHAR lightpurple = "\033[1;35m";
static DS_CONST_CHAR lightcyan = "\033[1;36m";
static DS_CONST_CHAR white = "\033[1;37m";

// background colors
static DS_CONST_CHAR bblack = "\033[40m";
static DS_CONST_CHAR bred = "\033[41m";
static DS_CONST_CHAR bgreen = "\033[42m";
static DS_CONST_CHAR bbrown = "\033[43m";
static DS_CONST_CHAR bblue = "\033[44m";
static DS_CONST_CHAR bpurple = "\033[45m";
static DS_CONST_CHAR bcyan = "\033[46m";
static DS_CONST_CHAR blightgray = "\033[47m";
// light background colors
static DS_CONST_CHAR bdarkgray = "\033[1;40m";
static DS_CONST_CHAR blightred = "\033[1;41m";
static DS_CONST_CHAR blightgreen = "\033[1;42m";
static DS_CONST_CHAR byellow = "\033[1;43m";
static DS_CONST_CHAR blightblue = "\033[1;44m";
static DS_CONST_CHAR blightpurple = "\033[1;45m";
static DS_CONST_CHAR blightcyan = "\033[1;46m";
static DS_CONST_CHAR bwhite = "\033[1;47m";
};
// modifiers
struct StreamModifiers {
static DS_CONST_CHAR normal = "\033[0m";
static DS_CONST_CHAR bold = "\033[1m";
static DS_CONST_CHAR italic = "\033[2m";
static DS_CONST_CHAR underline = "\033[4m";
static DS_CONST_CHAR blink = "\033[5m";
static DS_CONST_CHAR reverse = "\033[7m";
static DS_CONST_CHAR enditalic = "\033[22m";
static DS_CONST_CHAR endunderline = "\033[24m";
static DS_CONST_CHAR endblink = "\033[25m";
static DS_CONST_CHAR endreverse = "\033[27m";
#undef DS_CONST_CHAR
};
/**
 * @brief Chooses a color from a 256 color map for a foreground color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string color(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

/**
 * @brief Chooses a color from a 256 color map for a background color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string backcolor(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

// maybe you want to choose your own color
int templateColorChooser(int i) {
  return i % 256;
}

/**
 * @brief Highlights templates depending on the "template"-level.
 *
 * @param str The string containing the template string
 * @param maxlevel The maximal template-level the string is reduced to.
 * @returns A colored template string.
 */
std::string highlightTemplate(std::string str, int maxlevel = 10000) {
  if (maxlevel < 0)
    maxlevel = 0;
  int startindex = 0;
  int level = 0;
  for (size_t i = 0; i < str.size(); i++)
  {
    if (str[i] == '<')
    {
      level++;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(i, dummy);
      i += dummy.size();
      if (level == maxlevel)
        startindex = i + 1;
    } else if (str[i] == '>') {
      level--;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(++i, dummy);
      if (level + 1 == maxlevel)
      {
        int size = i - startindex - 1;
        str.erase(startindex, size);
        i = startindex + 1;
      }
      i += dummy.size();
    }
  }
  str += "\033[38;5;0m";
  return str;
} // highlightTemplate

/**
 * @brief A simple function highlighting a whole string in a specified foreground color.
 *
 * @param str The string you want to highlight.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightString(std::string str, int colornr = 0) {
  return "\033[38;5;" + toString(colornr % 256) + "m" + str + "\033[0m"; //"\033[38;5;0m";
}

std::string highlightString(const std::string string, const std::string color = Colors::red)
{
  return color + string + "\033[0m";
}

/**
 * @brief Highlights a substring of another string in a specified color.
 *
 * @param str The string where you want to highlight substrings.
 * @param substr The sub string you want to highlight in str.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {
  int index = str.find(substr, 0);

  while ( index != int(std::string::npos) )
  {
    std::string dummy = "\033[38;5;" + toString(colornr % 256) + "m";
    std::string dummy2 = "\033[38;5;0m";
    str.insert(index, dummy);
    str.insert(index + substr.size() + dummy.size(), dummy2);
    index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );
  }
  return str;
} // highlightSearchString

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // end of DUNE_COMMON_COLOR_HH

/** Copyright (c) 2012, Stefan Girke
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. 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.
   *
   * 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<commit_msg>[common.color] renamed highlichtString() to colorString()<commit_after>#ifndef DUNE_COMMON_COLOR_HH
#define DUNE_COMMON_COLOR_HH

#include <sstream>
#include <assert.h>
#include <iostream>

#ifdef __GNUC__
 #include <cxxabi.h>
#endif
#include <string>

#include <dune/stuff/common/string.hh>

namespace Dune {
namespace Stuff {
namespace Common {

/**
 * @brief namespace to define color constants that can be
 * used to print colored text in an output stream.
 *
 * * \todo this could go into libdune-stuff
 * @warning Some color codes might be unsupported by your terminal.
 */
struct Colors {

#define DS_CONST_CHAR const constexpr char*

// foreground colors
static DS_CONST_CHAR black = "\033[30m";
static DS_CONST_CHAR red = "\033[31m";
static DS_CONST_CHAR green = "\033[32m";
static DS_CONST_CHAR brown = "\033[33m";
static DS_CONST_CHAR blue = "\033[34m";
static DS_CONST_CHAR purple = "\033[35m";
static DS_CONST_CHAR cyan = "\033[36m";
static DS_CONST_CHAR lightgray = "\033[37m";
// light foreground colors
static DS_CONST_CHAR darkgray = "\033[1;30m";
static DS_CONST_CHAR lightred = "\033[1;31m";
static DS_CONST_CHAR lightgreen = "\033[1;32m";
static DS_CONST_CHAR yellow = "\033[1;33m";
static DS_CONST_CHAR lightblue = "\033[1;34m";
static DS_CONST_CHAR lightpurple = "\033[1;35m";
static DS_CONST_CHAR lightcyan = "\033[1;36m";
static DS_CONST_CHAR white = "\033[1;37m";

// background colors
static DS_CONST_CHAR bblack = "\033[40m";
static DS_CONST_CHAR bred = "\033[41m";
static DS_CONST_CHAR bgreen = "\033[42m";
static DS_CONST_CHAR bbrown = "\033[43m";
static DS_CONST_CHAR bblue = "\033[44m";
static DS_CONST_CHAR bpurple = "\033[45m";
static DS_CONST_CHAR bcyan = "\033[46m";
static DS_CONST_CHAR blightgray = "\033[47m";
// light background colors
static DS_CONST_CHAR bdarkgray = "\033[1;40m";
static DS_CONST_CHAR blightred = "\033[1;41m";
static DS_CONST_CHAR blightgreen = "\033[1;42m";
static DS_CONST_CHAR byellow = "\033[1;43m";
static DS_CONST_CHAR blightblue = "\033[1;44m";
static DS_CONST_CHAR blightpurple = "\033[1;45m";
static DS_CONST_CHAR blightcyan = "\033[1;46m";
static DS_CONST_CHAR bwhite = "\033[1;47m";
};
// modifiers
struct StreamModifiers {
static DS_CONST_CHAR normal = "\033[0m";
static DS_CONST_CHAR bold = "\033[1m";
static DS_CONST_CHAR italic = "\033[2m";
static DS_CONST_CHAR underline = "\033[4m";
static DS_CONST_CHAR blink = "\033[5m";
static DS_CONST_CHAR reverse = "\033[7m";
static DS_CONST_CHAR enditalic = "\033[22m";
static DS_CONST_CHAR endunderline = "\033[24m";
static DS_CONST_CHAR endblink = "\033[25m";
static DS_CONST_CHAR endreverse = "\033[27m";
#undef DS_CONST_CHAR
};
/**
 * @brief Chooses a color from a 256 color map for a foreground color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string color(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

/**
 * @brief Chooses a color from a 256 color map for a background color.
 *
 * @param i The color number between 0 and 255.
 * @returns A string describing a color code.
 */
std::string backcolor(int i) {
  return "\033[38;5;" + toString(i) + "m";
}

// maybe you want to choose your own color
int templateColorChooser(int i) {
  return i % 256;
}

/**
 * @brief Highlights templates depending on the "template"-level.
 *
 * @param str The string containing the template string
 * @param maxlevel The maximal template-level the string is reduced to.
 * @returns A colored template string.
 */
std::string highlightTemplate(std::string str, int maxlevel = 10000) {
  if (maxlevel < 0)
    maxlevel = 0;
  int startindex = 0;
  int level = 0;
  for (size_t i = 0; i < str.size(); i++)
  {
    if (str[i] == '<')
    {
      level++;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(i, dummy);
      i += dummy.size();
      if (level == maxlevel)
        startindex = i + 1;
    } else if (str[i] == '>') {
      level--;
      std::string dummy = "\033[38;5;" + toString( templateColorChooser(level) ) + "m";
      str.insert(++i, dummy);
      if (level + 1 == maxlevel)
      {
        int size = i - startindex - 1;
        str.erase(startindex, size);
        i = startindex + 1;
      }
      i += dummy.size();
    }
  }
  str += "\033[38;5;0m";
  return str;
} // highlightTemplate

/**
 * @brief A simple function highlighting a whole string in a specified foreground color.
 *
 * @param str The string you want to highlight.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightString(std::string str, int colornr = 0) {
  return "\033[38;5;" + toString(colornr % 256) + "m" + str + "\033[0m"; //"\033[38;5;0m";
}

std::string colorString(const std::string string, const std::string color = Colors::brown)
{
  return color + string + "\033[0m";
}

/**
 * @brief Highlights a substring of another string in a specified color.
 *
 * @param str The string where you want to highlight substrings.
 * @param substr The sub string you want to highlight in str.
 * @param colornr A color number from a 256 color map between 0 and 255.
 * @returns The highlighted string.
 */
std::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {
  int index = str.find(substr, 0);

  while ( index != int(std::string::npos) )
  {
    std::string dummy = "\033[38;5;" + toString(colornr % 256) + "m";
    std::string dummy2 = "\033[38;5;0m";
    str.insert(index, dummy);
    str.insert(index + substr.size() + dummy.size(), dummy2);
    index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );
  }
  return str;
} // highlightSearchString

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // end of DUNE_COMMON_COLOR_HH

/** Copyright (c) 2012, Stefan Girke
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. 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.
   *
   * 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.
   *
   * The views and conclusions contained in the software and documentation are those
   * of the authors and should not be interpreted as representing official policies,
   * either expressed or implied, of the FreeBSD Project.
   **/
<|endoftext|>


<commit_before>#include "UpdaterWindow.h"

#include "../3RVX/3RVX.h"
#include "../3RVX/Logger.h"
#include "../3RVX/CommCtl.h"
#include "../3RVX/NotifyIcon.h"
#include "../3RVX/Settings.h"
#include "resource.h"
#include "Updater.h"

UpdaterWindow::UpdaterWindow() :
Window(L"3RVX-UpdateWindow") {
    HRESULT hr;
    hr = LoadIconMetric(
        Window::InstanceHandle(),
        MAKEINTRESOURCE(IDI_MAINICON),
        LIM_SMALL,
        &_smallIcon);
    if (hr != S_OK) {
        CLOG(L"Could not load notification icon");
    }

    hr = LoadIconMetric(
        Window::InstanceHandle(),
        MAKEINTRESOURCE(IDI_MAINICON),
        LIM_LARGE,
        &_largeIcon);
    if (hr != S_OK) {
        CLOG(L"Could not load large notification icon");
    }

    _menu = CreatePopupMenu();

    InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, L"Install");
    InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, L"Ignore version");
    InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, L"Remind me later");

    _menuFlags = TPM_RIGHTBUTTON;
    if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {
        _menuFlags |= TPM_RIGHTALIGN;
    } else {
        _menuFlags |= TPM_LEFTALIGN;
    }
}

UpdaterWindow::~UpdaterWindow() {
    delete _notifyIcon;
    DestroyIcon(_smallIcon);
    DestroyIcon(_largeIcon);
}

LRESULT UpdaterWindow::WndProc(
    HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

    if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
        switch (wParam) {
        case _3RVX::MSG_UPDATEICON:
            _settings = Settings::Instance();
            _settings->Load();

            /* Set that we just checked for updates now */
            _settings->LastUpdateCheckNow();
            _settings->Save();

            std::pair<int, int> newVersion = Updater::RemoteVersion();
            _versionString = Updater::VersionToString(newVersion);
            if (newVersion.first <= 0
                    || _versionString == _settings->IgnoreUpdate()) {
                SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
                break;
            }

            CLOG(L"Creating update icon");
            _notifyIcon = new NotifyIcon(
                Window::Handle(),
                L"Update Available",
                _smallIcon);

            CLOG(L"Launching balloon notification");
            _notifyIcon->Balloon(L"Update Available",
                L"3RVX " + _versionString, _largeIcon);
            break;
        }

    }

    return Window::WndProc(hWnd, message, wParam, lParam);
}

void UpdaterWindow::DoModal() {
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}<commit_msg>Implement the popup menu<commit_after>#include "UpdaterWindow.h"

#include "../3RVX/3RVX.h"
#include "../3RVX/Logger.h"
#include "../3RVX/CommCtl.h"
#include "../3RVX/NotifyIcon.h"
#include "../3RVX/Settings.h"
#include "resource.h"
#include "Updater.h"

UpdaterWindow::UpdaterWindow() :
Window(L"3RVX-UpdateWindow") {
    HRESULT hr;
    hr = LoadIconMetric(
        Window::InstanceHandle(),
        MAKEINTRESOURCE(IDI_MAINICON),
        LIM_SMALL,
        &_smallIcon);
    if (hr != S_OK) {
        CLOG(L"Could not load notification icon");
    }

    hr = LoadIconMetric(
        Window::InstanceHandle(),
        MAKEINTRESOURCE(IDI_MAINICON),
        LIM_LARGE,
        &_largeIcon);
    if (hr != S_OK) {
        CLOG(L"Could not load large notification icon");
    }

    _menu = CreatePopupMenu();

    InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, L"Install");
    InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, L"Ignore version");
    InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, L"Remind me later");

    _menuFlags = TPM_RIGHTBUTTON;
    if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {
        _menuFlags |= TPM_RIGHTALIGN;
    } else {
        _menuFlags |= TPM_LEFTALIGN;
    }
}

UpdaterWindow::~UpdaterWindow() {
    delete _notifyIcon;
    DestroyIcon(_smallIcon);
    DestroyIcon(_largeIcon);
}

LRESULT UpdaterWindow::WndProc(
    HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {

    if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
        switch (wParam) {
        case _3RVX::MSG_UPDATEICON:
            _settings = Settings::Instance();
            _settings->Load();

            /* Set that we just checked for updates now */
            _settings->LastUpdateCheckNow();
            _settings->Save();

            std::pair<int, int> newVersion = Updater::RemoteVersion();
            _versionString = Updater::VersionToString(newVersion);
            if (newVersion.first <= 0
                    || _versionString == _settings->IgnoreUpdate()) {
                SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
                break;
            }

            CLOG(L"Creating update icon");
            _notifyIcon = new NotifyIcon(
                Window::Handle(),
                L"Update Available",
                _smallIcon);

            CLOG(L"Launching balloon notification");
            _notifyIcon->Balloon(L"Update Available",
                L"3RVX " + _versionString, _largeIcon);
            break;
        }
    } else if (message == MSG_NOTIFYICON) {
        if (lParam == WM_LBUTTONUP
            || lParam == WM_RBUTTONUP
            || lParam == NIN_BALLOONUSERCLICK) {
            POINT p;
            GetCursorPos(&p);
            SetForegroundWindow(hWnd);
            TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y,
                Window::Handle(), NULL);
            PostMessage(hWnd, WM_NULL, 0, 0);
        }

    }

    return Window::WndProc(hWnd, message, wParam, lParam);
}

void UpdaterWindow::DoModal() {
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbOSMDownloader.h"

#include <iostream>
#include "otbCommandLineArgumentParser.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"

#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataProperties.h"
#include "otbOSMDataToVectorDataGenerator.h"
#include "otbVectorDataFileWriter.h"

namespace otb
{

int OSMDownloader::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("OSMDownloader");
  descriptor->SetDescription("Generate a vector data from OSM on the input image extend");
  descriptor->AddOption("InputImage", "Support to estimate the models on",
                        "in", 1, true, ApplicationDescriptor::InputImage);
  descriptor->AddOption("OSMKey", "OSM key (highway, building...)",
                        "key", 1, true, ApplicationDescriptor::String);
  descriptor->AddOption("OSMValue", "OSM Value (motorway, footway...)",
                        "val", 1, false, ApplicationDescriptor::String);
  descriptor->AddOption("DEMDirectory", "DEM directory",
                        "dem", 1, false, ApplicationDescriptor::DirectoryName);
  descriptor->AddOption("Output", "OutputVectorData",
                        "out", 1, false, ApplicationDescriptor::FileName);
  return EXIT_SUCCESS;
}

int OSMDownloader::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::OSMDataToVectorDataGenerator           VectorDataProviderType;
  typedef VectorDataProviderType::VectorDataType      VectorDataType;
  typedef VectorDataType::ValuePrecisionType          PrecisionType;
  typedef VectorDataType::PrecisionType               CoordRepType;

  typedef otb::VectorImage<PrecisionType , 2>         ImageType;
  typedef otb::ImageFileReader<ImageType>             ImageReaderType;

  typedef otb::ImageToEnvelopeVectorDataFilter<ImageType, VectorDataType>
                                                      EnvelopeFilterType;
  typedef otb::VectorDataProperties<VectorDataType>   VectorDataPropertiesType;
  typedef otb::VectorDataFileWriter<VectorDataType>   VectorDataWriterType;

  //Instantiate
  ImageReaderType::Pointer                 imgReader = ImageReaderType::New();
  EnvelopeFilterType::Pointer         envelopeFilter = EnvelopeFilterType::New();
  VectorDataProviderType::Pointer     vdOSMGenerator = VectorDataProviderType::New();
  VectorDataPropertiesType::Pointer     vdProperties = VectorDataPropertiesType::New();
  VectorDataWriterType::Pointer             vdWriter = VectorDataWriterType::New();

  //Read the image
  imgReader->SetFileName(parseResult->GetParameterString("InputImage"));
  imgReader->UpdateOutputInformation();

  //Generate the envelope
  envelopeFilter->SetInput(imgReader->GetOutput()); //->Output in WGS84
  if (parseResult->IsOptionPresent("CriterionFormula"))
    {
    envelopeFilter->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory"));
    }
  envelopeFilter->Update();

  vdProperties->SetVectorDataObject(envelopeFilter->GetOutput());
  vdProperties->ComputeBoundingRegion();

  double north, south, east, west;
  north = vdProperties->GetBoundingRegion().GetIndex()[1]
           + vdProperties->GetBoundingRegion().GetSize()[1];
  south = vdProperties->GetBoundingRegion().GetIndex()[1];
  east  = vdProperties->GetBoundingRegion().GetIndex()[0]
           + vdProperties->GetBoundingRegion().GetSize()[0];
  west  = vdProperties->GetBoundingRegion().GetIndex()[0];

  /*
  std::cout << "north : " << north << std::endl;
  std::cout << "south : " << south << std::endl;
  std::cout << "east  : " << east  << std::endl;
  std::cout << "west  : " << west  << std::endl;
  */

  vdOSMGenerator->SetNorth(north);
  vdOSMGenerator->SetSouth(south);
  vdOSMGenerator->SetEast(east);
  vdOSMGenerator->SetWest(west);

  try
  {
    vdOSMGenerator->Update();
  }
  catch ( itk::ExceptionObject & err )
  {
    std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString("OSMKey"))->Size()-3
      << std::endl;

  if (parseResult->IsOptionPresent("OSMValue"))
    {
    vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString("OSMKey"),
                                                           parseResult->GetParameterString("OSMValue")));
    }
  else
    {
    vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString("OSMKey")));
    }

  vdWriter->SetFileName(parseResult->GetParameterString("Output"));
  vdWriter->Update();

  return EXIT_SUCCESS;
}

}
<commit_msg>ENH:enriched output message for OSMDownloader-cli application<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbOSMDownloader.h"

#include <iostream>
#include "otbCommandLineArgumentParser.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"

#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataProperties.h"
#include "otbOSMDataToVectorDataGenerator.h"
#include "otbVectorDataFileWriter.h"

namespace otb
{

int OSMDownloader::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("OSMDownloader");
  descriptor->SetDescription("Generate a vector data from OSM on the input image extend");
  descriptor->AddOption("InputImage", "Support to estimate the models on",
                        "in", 1, true, ApplicationDescriptor::InputImage);
  descriptor->AddOption("OSMKey", "OSM key (highway, building...)",
                        "key", 1, true, ApplicationDescriptor::String);
  descriptor->AddOption("OSMValue", "OSM Value (motorway, footway...)",
                        "val", 1, false, ApplicationDescriptor::String);
  descriptor->AddOption("DEMDirectory", "DEM directory",
                        "dem", 1, false, ApplicationDescriptor::DirectoryName);
  descriptor->AddOption("Output", "OutputVectorData",
                        "out", 1, false, ApplicationDescriptor::FileName);
  return EXIT_SUCCESS;
}

int OSMDownloader::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::OSMDataToVectorDataGenerator           VectorDataProviderType;
  typedef VectorDataProviderType::VectorDataType      VectorDataType;
  typedef VectorDataType::ValuePrecisionType          PrecisionType;
  typedef VectorDataType::PrecisionType               CoordRepType;

  typedef otb::VectorImage<PrecisionType , 2>         ImageType;
  typedef otb::ImageFileReader<ImageType>             ImageReaderType;

  typedef otb::ImageToEnvelopeVectorDataFilter<ImageType, VectorDataType>
                                                      EnvelopeFilterType;
  typedef otb::VectorDataProperties<VectorDataType>   VectorDataPropertiesType;
  typedef otb::VectorDataFileWriter<VectorDataType>   VectorDataWriterType;

  //Instantiate
  ImageReaderType::Pointer                 imgReader = ImageReaderType::New();
  EnvelopeFilterType::Pointer         envelopeFilter = EnvelopeFilterType::New();
  VectorDataProviderType::Pointer     vdOSMGenerator = VectorDataProviderType::New();
  VectorDataPropertiesType::Pointer     vdProperties = VectorDataPropertiesType::New();
  VectorDataWriterType::Pointer             vdWriter = VectorDataWriterType::New();

  //Read the image
  imgReader->SetFileName(parseResult->GetParameterString("InputImage"));
  imgReader->UpdateOutputInformation();

  //Generate the envelope
  envelopeFilter->SetInput(imgReader->GetOutput()); //->Output in WGS84
  if (parseResult->IsOptionPresent("CriterionFormula"))
    {
    envelopeFilter->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory"));
    }
  envelopeFilter->Update();

  vdProperties->SetVectorDataObject(envelopeFilter->GetOutput());
  vdProperties->ComputeBoundingRegion();

  double north, south, east, west;
  north = vdProperties->GetBoundingRegion().GetIndex()[1]
           + vdProperties->GetBoundingRegion().GetSize()[1];
  south = vdProperties->GetBoundingRegion().GetIndex()[1];
  east  = vdProperties->GetBoundingRegion().GetIndex()[0]
           + vdProperties->GetBoundingRegion().GetSize()[0];
  west  = vdProperties->GetBoundingRegion().GetIndex()[0];

  /*
  std::cout << "north : " << north << std::endl;
  std::cout << "south : " << south << std::endl;
  std::cout << "east  : " << east  << std::endl;
  std::cout << "west  : " << west  << std::endl;
  */

  vdOSMGenerator->SetNorth(north);
  vdOSMGenerator->SetSouth(south);
  vdOSMGenerator->SetEast(east);
  vdOSMGenerator->SetWest(west);

  try
  {
    vdOSMGenerator->Update();
  }
  catch ( itk::ExceptionObject & err )
  {
    std::cout << "Exception itk::ExceptionObject raised !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString("OSMKey"))->Size()-3
      << " vector elements retrieved" << std::endl;

  if (parseResult->IsOptionPresent("OSMValue"))
    {
    vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString("OSMKey"),
                                                           parseResult->GetParameterString("OSMValue")));
    }
  else
    {
    vdWriter->SetInput(vdOSMGenerator->GetVectorDataByName(parseResult->GetParameterString("OSMKey")));
    }

  vdWriter->SetFileName(parseResult->GetParameterString("Output"));
  vdWriter->Update();

  return EXIT_SUCCESS;
}

}
<|endoftext|>


<commit_before>/*
 * Copyright 2009, 2010 Google Inc.
 *
 * 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 <esnpapi.h>
#include <org/w3c/dom.h>

#include <assert.h>

std::map<const std::string, Object* (*)(ProxyObject object)> ProxyControl::proxyConstructorMap;

ProxyControl::ProxyControl(NPP npp) :
    npp(npp),
    nestingCount(1)
{
}

ProxyControl::~ProxyControl()
{
    // TODO: Release objects in newList and oldList
}

Object* ProxyControl::createProxy(NPObject* object, const Reflect::Type type)
{
    if (!object)
    {
        return 0;
    }

    std::string className = getInterfaceName(npp, object);
    if (className == "Object")
    {
        // TODO: We should define 'Object' interface
        return 0;
    }

    bool usedHint = false;
    for (;;)
    {
        std::map<const std::string, Object* (*)(ProxyObject object)>::iterator it;
        it = proxyConstructorMap.find(className);
        if (it != proxyConstructorMap.end())
        {
            ProxyObject browserObject(object, npp);
            if (Object* object = (*it).second(browserObject))
            {
                return track(object);
            }
        }
        if (!type.isObject() || usedHint)
        {
            break;
        }
        className = type.getQualifiedName();
        size_t pos = className.rfind(':');
        if (pos != std::string::npos)
        {
            className = className.substr(pos + 1);
            printf("%s: use the class name '%s' as hinted.\n", __func__, className.c_str());
        }
        usedHint = true;
    }
    return 0;
}

long ProxyControl::enter()
{
    return ++nestingCount;
}

long ProxyControl::leave()
{
    --nestingCount;
    assert(0 <= nestingCount);
    if (nestingCount == 0)
    {
        while (!newList.empty())
        {
            Object* object = newList.front();
            newList.pop_front();
            if (0 < object->release())
            {
                oldList.push_back(object);
            }
        }
    }
    return nestingCount;
}

void ProxyControl::registerMetaData(const char* meta, Object* (*createProxy)(ProxyObject object), const char* alias)
{
    Reflect::Interface interface(meta);
    std::string name = interface.getName();
    if (alias)
    {
        name = alias;
    }
    proxyConstructorMap[name] = createProxy;
    printf("%s\n", name.c_str());
}

ProxyObject::ProxyObject(NPObject* object, NPP npp) :
    object(object),
    npp(npp),
    count(0)
{
}

ProxyObject::ProxyObject(const ProxyObject& original) :
    object(original.object),
    npp(original.npp),
    count(original.count)
{
}

ProxyObject::~ProxyObject()
{
    // TODO: Remove this from newList or oldList is it is still included
}

unsigned int ProxyObject::retain()
{
    NPN_RetainObject(object);
    return ++count;
}

unsigned int ProxyObject::release()
{
    if (0 < count)
    {
        NPN_ReleaseObject(object);
        --count;
    }
    if (count == 0)
    {
        delete this;
        return 0;
    }
    return count;
}

unsigned int ProxyObject::mark()
{
    return ++count;
}

PluginInstance::PluginInstance(NPP npp, NPObject* window) :
    proxyControl(npp),
    stubControl(npp),
    window(0)
{
    npp->pdata = this;
    this->window = interface_cast<org::w3c::dom::html::Window*>(proxyControl.createProxy(window, Reflect::Type("O14::html::Window")));
    if (this->window)
    {
        ProxyObject* proxy = interface_cast<ProxyObject*>(this->window);
        proxy->mark();
        proxy->retain();
    }
}

PluginInstance::~PluginInstance()
{
    if (window)
    {
        window->release();
    }
}

<commit_msg>(~ProxyObject) : Fix a typo.<commit_after>/*
 * Copyright 2009, 2010 Google Inc.
 *
 * 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 <esnpapi.h>
#include <org/w3c/dom.h>

#include <assert.h>

std::map<const std::string, Object* (*)(ProxyObject object)> ProxyControl::proxyConstructorMap;

ProxyControl::ProxyControl(NPP npp) :
    npp(npp),
    nestingCount(1)
{
}

ProxyControl::~ProxyControl()
{
    // TODO: Release objects in newList and oldList
}

Object* ProxyControl::createProxy(NPObject* object, const Reflect::Type type)
{
    if (!object)
    {
        return 0;
    }

    std::string className = getInterfaceName(npp, object);
    if (className == "Object")
    {
        // TODO: We should define 'Object' interface
        return 0;
    }

    bool usedHint = false;
    for (;;)
    {
        std::map<const std::string, Object* (*)(ProxyObject object)>::iterator it;
        it = proxyConstructorMap.find(className);
        if (it != proxyConstructorMap.end())
        {
            ProxyObject browserObject(object, npp);
            if (Object* object = (*it).second(browserObject))
            {
                return track(object);
            }
        }
        if (!type.isObject() || usedHint)
        {
            break;
        }
        className = type.getQualifiedName();
        size_t pos = className.rfind(':');
        if (pos != std::string::npos)
        {
            className = className.substr(pos + 1);
            printf("%s: use the class name '%s' as hinted.\n", __func__, className.c_str());
        }
        usedHint = true;
    }
    return 0;
}

long ProxyControl::enter()
{
    return ++nestingCount;
}

long ProxyControl::leave()
{
    --nestingCount;
    assert(0 <= nestingCount);
    if (nestingCount == 0)
    {
        while (!newList.empty())
        {
            Object* object = newList.front();
            newList.pop_front();
            if (0 < object->release())
            {
                oldList.push_back(object);
            }
        }
    }
    return nestingCount;
}

void ProxyControl::registerMetaData(const char* meta, Object* (*createProxy)(ProxyObject object), const char* alias)
{
    Reflect::Interface interface(meta);
    std::string name = interface.getName();
    if (alias)
    {
        name = alias;
    }
    proxyConstructorMap[name] = createProxy;
    printf("%s\n", name.c_str());
}

ProxyObject::ProxyObject(NPObject* object, NPP npp) :
    object(object),
    npp(npp),
    count(0)
{
}

ProxyObject::ProxyObject(const ProxyObject& original) :
    object(original.object),
    npp(original.npp),
    count(original.count)
{
}

ProxyObject::~ProxyObject()
{
    // TODO: Remove this from newList or oldList if it is still included
}

unsigned int ProxyObject::retain()
{
    NPN_RetainObject(object);
    return ++count;
}

unsigned int ProxyObject::release()
{
    if (0 < count)
    {
        NPN_ReleaseObject(object);
        --count;
    }
    if (count == 0)
    {
        delete this;
        return 0;
    }
    return count;
}

unsigned int ProxyObject::mark()
{
    return ++count;
}

PluginInstance::PluginInstance(NPP npp, NPObject* window) :
    proxyControl(npp),
    stubControl(npp),
    window(0)
{
    npp->pdata = this;
    this->window = interface_cast<org::w3c::dom::html::Window*>(proxyControl.createProxy(window, Reflect::Type("O14::html::Window")));
    if (this->window)
    {
        ProxyObject* proxy = interface_cast<ProxyObject*>(this->window);
        proxy->mark();
        proxy->retain();
    }
}

PluginInstance::~PluginInstance()
{
    if (window)
    {
        window->release();
    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2011 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/debugger/devtools_netlog_observer.h"

#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/io_thread.h"
#include "content/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/http/http_net_log_params.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
#include "webkit/glue/resource_loader_bridge.h"

const size_t kMaxNumEntries = 1000;

DevToolsNetLogObserver* DevToolsNetLogObserver::instance_ = NULL;

DevToolsNetLogObserver::DevToolsNetLogObserver(ChromeNetLog* chrome_net_log)
    : ChromeNetLog::ThreadSafeObserver(net::NetLog::LOG_ALL_BUT_BYTES),
      chrome_net_log_(chrome_net_log) {
  chrome_net_log_->AddObserver(this);
}

DevToolsNetLogObserver::~DevToolsNetLogObserver() {
  chrome_net_log_->RemoveObserver(this);
}

DevToolsNetLogObserver::ResourceInfo*
DevToolsNetLogObserver::GetResourceInfo(uint32 id) {
  RequestToInfoMap::iterator it = request_to_info_.find(id);
  if (it != request_to_info_.end())
    return it->second;
  return NULL;
}

void DevToolsNetLogObserver::OnAddEntry(net::NetLog::EventType type,
                                        const base::TimeTicks& time,
                                        const net::NetLog::Source& source,
                                        net::NetLog::EventPhase phase,
                                        net::NetLog::EventParameters* params) {
  // The events that the Observer is interested in only occur on the IO thread.
  if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
    return;

  // The events that the Observer is interested in only occur on the IO thread.
  if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
    return;
  if (source.type == net::NetLog::SOURCE_URL_REQUEST)
    OnAddURLRequestEntry(type, time, source, phase, params);
  else if (source.type == net::NetLog::SOURCE_HTTP_STREAM_JOB)
    OnAddHTTPStreamJobEntry(type, time, source, phase, params);
  else if (source.type == net::NetLog::SOURCE_SOCKET)
    OnAddSocketEntry(type, time, source, phase, params);
}

void DevToolsNetLogObserver::OnAddURLRequestEntry(
    net::NetLog::EventType type,
    const base::TimeTicks& time,
    const net::NetLog::Source& source,
    net::NetLog::EventPhase phase,
    net::NetLog::EventParameters* params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  bool is_begin = phase == net::NetLog::PHASE_BEGIN;
  bool is_end = phase == net::NetLog::PHASE_END;

  if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
    if (is_begin) {
      int load_flags = static_cast<
          net::URLRequestStartEventParameters*>(params)->load_flags();
      if (!(load_flags & net::LOAD_REPORT_RAW_HEADERS))
        return;

      if (request_to_info_.size() > kMaxNumEntries) {
        LOG(WARNING) << "The raw headers observer url request count has grown "
                        "larger than expected, resetting";
        request_to_info_.clear();
      }

      request_to_info_[source.id] = new ResourceInfo();

      if (request_to_encoded_data_length_.size() > kMaxNumEntries) {
        LOG(WARNING) << "The encoded data length observer url request count "
                        "has grown larger than expected, resetting";
        request_to_encoded_data_length_.clear();
      }

      request_to_encoded_data_length_[source.id] = 0;
    }
    return;
  } else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {
    // Cleanup records based on the TYPE_REQUEST_ALIVE entry.
    if (is_end) {
      request_to_info_.erase(source.id);
      request_to_encoded_data_length_.erase(source.id);
    }
    return;
  }

  ResourceInfo* info = GetResourceInfo(source.id);
  if (!info)
    return;

  switch (type) {
    case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS: {
      net::NetLogHttpRequestParameter* request_parameter =
          static_cast<net::NetLogHttpRequestParameter*>(params);
      const net::HttpRequestHeaders &request_headers =
          request_parameter->GetHeaders();
      for (net::HttpRequestHeaders::Iterator it(request_headers);
           it.GetNext();) {
        info->request_headers.push_back(std::make_pair(it.name(),
                                                       it.value()));
      }
      info->request_headers_text =
          request_parameter->GetLine() +
          request_parameter->GetHeaders().ToString();
      break;
    }
    case net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS: {
      const net::HttpResponseHeaders& response_headers =
          static_cast<net::NetLogHttpResponseParameter*>(params)->GetHeaders();
      info->http_status_code = response_headers.response_code();
      info->http_status_text = response_headers.GetStatusText();
      std::string name, value;
      for (void* it = NULL;
           response_headers.EnumerateHeaderLines(&it, &name, &value); ) {
        info->response_headers.push_back(std::make_pair(name, value));
      }
      info->response_headers_text =
          net::HttpUtil::ConvertHeadersBackToHTTPResponse(
              response_headers.raw_headers());
      break;
    }
    case net::NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_JOB: {
      uint32 http_stream_job_id = static_cast<net::NetLogSourceParameter*>(
          params)->value().id;
      HTTPStreamJobToSocketMap::iterator it =
          http_stream_job_to_socket_.find(http_stream_job_id);
      if (it == http_stream_job_to_socket_.end())
        return;
      uint32 socket_id = it->second;

      if (socket_to_request_.size() > kMaxNumEntries) {
        LOG(WARNING) << "The url request observer socket count has grown "
                        "larger than expected, resetting";
        socket_to_request_.clear();
      }

      socket_to_request_[socket_id] = source.id;
      http_stream_job_to_socket_.erase(http_stream_job_id);
      break;
    }
    default:
      break;
  }
}

void DevToolsNetLogObserver::OnAddHTTPStreamJobEntry(
    net::NetLog::EventType type,
    const base::TimeTicks& time,
    const net::NetLog::Source& source,
    net::NetLog::EventPhase phase,
    net::NetLog::EventParameters* params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (type == net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET) {
    uint32 socket_id = static_cast<net::NetLogSourceParameter*>(
      params)->value().id;

    // Prevents us from passively growing the memory unbounded in
    // case something went wrong. Should not happen.
    if (http_stream_job_to_socket_.size() > kMaxNumEntries) {
      LOG(WARNING) << "The load timing observer http stream job count "
                      "has grown larger than expected, resetting";
      http_stream_job_to_socket_.clear();
    }
    http_stream_job_to_socket_[source.id] = socket_id;
  }
}

void DevToolsNetLogObserver::OnAddSocketEntry(
    net::NetLog::EventType type,
    const base::TimeTicks& time,
    const net::NetLog::Source& source,
    net::NetLog::EventPhase phase,
    net::NetLog::EventParameters* params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  bool is_end = phase == net::NetLog::PHASE_END;

  SocketToRequestMap::iterator it = socket_to_request_.find(source.id);
  if (it == socket_to_request_.end())
    return;
  uint32 request_id = it->second;

  if (type == net::NetLog::TYPE_SOCKET_IN_USE) {
    if (is_end)
      socket_to_request_.erase(source.id);
    return;
  }

  RequestToEncodedDataLengthMap::iterator encoded_data_length_it =
      request_to_encoded_data_length_.find(request_id);
  if (encoded_data_length_it == request_to_encoded_data_length_.end())
    return;

  if (net::NetLog::TYPE_SOCKET_BYTES_RECEIVED == type) {
    int byte_count = 0;
    scoped_ptr<Value> value(params->ToValue());
    if (!value->IsType(Value::TYPE_DICTIONARY))
      return;

    DictionaryValue* dValue = static_cast<DictionaryValue*>(value.get());
    if (!dValue->GetInteger("byte_count", &byte_count))
      return;

    encoded_data_length_it->second += byte_count;
  }
}

void DevToolsNetLogObserver::Attach(IOThread* io_thread) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!instance_);

  instance_ = new DevToolsNetLogObserver(io_thread->net_log());
}

void DevToolsNetLogObserver::Detach() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(instance_);

  delete instance_;
  instance_ = NULL;
}

DevToolsNetLogObserver* DevToolsNetLogObserver::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  return instance_;
}

// static
void DevToolsNetLogObserver::PopulateResponseInfo(net::URLRequest* request,
                                                  ResourceResponse* response) {
  if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))
    return;

  uint32 source_id = request->net_log().source().id;
  DevToolsNetLogObserver* dev_tools_net_log_observer =
      DevToolsNetLogObserver::GetInstance();
  if (dev_tools_net_log_observer == NULL)
    return;
  response->response_head.devtools_info =
      dev_tools_net_log_observer->GetResourceInfo(source_id);
}

// static
int DevToolsNetLogObserver::GetAndResetEncodedDataLength(
    net::URLRequest* request) {
  if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))
    return -1;

  uint32 source_id = request->net_log().source().id;
  DevToolsNetLogObserver* dev_tools_net_log_observer =
      DevToolsNetLogObserver::GetInstance();
  if (dev_tools_net_log_observer == NULL)
    return -1;

  RequestToEncodedDataLengthMap::iterator it =
      dev_tools_net_log_observer->request_to_encoded_data_length_.find(
          source_id);
  if (it == dev_tools_net_log_observer->request_to_encoded_data_length_.end())
    return -1;
  int encoded_data_length = it->second;
  it->second = 0;
  return encoded_data_length;
}
<commit_msg>Clear devtools headers when url_request is reused for several HTTP requests<commit_after>// Copyright (c) 2011 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/debugger/devtools_netlog_observer.h"

#include "base/string_tokenizer.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/io_thread.h"
#include "content/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/http/http_net_log_params.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
#include "webkit/glue/resource_loader_bridge.h"

const size_t kMaxNumEntries = 1000;

DevToolsNetLogObserver* DevToolsNetLogObserver::instance_ = NULL;

DevToolsNetLogObserver::DevToolsNetLogObserver(ChromeNetLog* chrome_net_log)
    : ChromeNetLog::ThreadSafeObserver(net::NetLog::LOG_ALL_BUT_BYTES),
      chrome_net_log_(chrome_net_log) {
  chrome_net_log_->AddObserver(this);
}

DevToolsNetLogObserver::~DevToolsNetLogObserver() {
  chrome_net_log_->RemoveObserver(this);
}

DevToolsNetLogObserver::ResourceInfo*
DevToolsNetLogObserver::GetResourceInfo(uint32 id) {
  RequestToInfoMap::iterator it = request_to_info_.find(id);
  if (it != request_to_info_.end())
    return it->second;
  return NULL;
}

void DevToolsNetLogObserver::OnAddEntry(net::NetLog::EventType type,
                                        const base::TimeTicks& time,
                                        const net::NetLog::Source& source,
                                        net::NetLog::EventPhase phase,
                                        net::NetLog::EventParameters* params) {
  // The events that the Observer is interested in only occur on the IO thread.
  if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
    return;

  // The events that the Observer is interested in only occur on the IO thread.
  if (!BrowserThread::CurrentlyOn(BrowserThread::IO))
    return;
  if (source.type == net::NetLog::SOURCE_URL_REQUEST)
    OnAddURLRequestEntry(type, time, source, phase, params);
  else if (source.type == net::NetLog::SOURCE_HTTP_STREAM_JOB)
    OnAddHTTPStreamJobEntry(type, time, source, phase, params);
  else if (source.type == net::NetLog::SOURCE_SOCKET)
    OnAddSocketEntry(type, time, source, phase, params);
}

void DevToolsNetLogObserver::OnAddURLRequestEntry(
    net::NetLog::EventType type,
    const base::TimeTicks& time,
    const net::NetLog::Source& source,
    net::NetLog::EventPhase phase,
    net::NetLog::EventParameters* params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  bool is_begin = phase == net::NetLog::PHASE_BEGIN;
  bool is_end = phase == net::NetLog::PHASE_END;

  if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
    if (is_begin) {
      int load_flags = static_cast<
          net::URLRequestStartEventParameters*>(params)->load_flags();
      if (!(load_flags & net::LOAD_REPORT_RAW_HEADERS))
        return;

      if (request_to_info_.size() > kMaxNumEntries) {
        LOG(WARNING) << "The raw headers observer url request count has grown "
                        "larger than expected, resetting";
        request_to_info_.clear();
      }

      request_to_info_[source.id] = new ResourceInfo();

      if (request_to_encoded_data_length_.size() > kMaxNumEntries) {
        LOG(WARNING) << "The encoded data length observer url request count "
                        "has grown larger than expected, resetting";
        request_to_encoded_data_length_.clear();
      }

      request_to_encoded_data_length_[source.id] = 0;
    }
    return;
  } else if (type == net::NetLog::TYPE_REQUEST_ALIVE) {
    // Cleanup records based on the TYPE_REQUEST_ALIVE entry.
    if (is_end) {
      request_to_info_.erase(source.id);
      request_to_encoded_data_length_.erase(source.id);
    }
    return;
  }

  ResourceInfo* info = GetResourceInfo(source.id);
  if (!info)
    return;

  switch (type) {
    case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS: {
      net::NetLogHttpRequestParameter* request_parameter =
          static_cast<net::NetLogHttpRequestParameter*>(params);
      const net::HttpRequestHeaders &request_headers =
          request_parameter->GetHeaders();

      // We need to clear headers in case the same url_request is reused for
      // several http requests (e.g. see http://crbug.com/80157).
      info->request_headers.clear();

      for (net::HttpRequestHeaders::Iterator it(request_headers);
           it.GetNext();) {
        info->request_headers.push_back(std::make_pair(it.name(),
                                                       it.value()));
      }
      info->request_headers_text =
          request_parameter->GetLine() +
          request_parameter->GetHeaders().ToString();
      break;
    }
    case net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS: {
      const net::HttpResponseHeaders& response_headers =
          static_cast<net::NetLogHttpResponseParameter*>(params)->GetHeaders();
      info->http_status_code = response_headers.response_code();
      info->http_status_text = response_headers.GetStatusText();
      std::string name, value;

      // We need to clear headers in case the same url_request is reused for
      // several http requests (e.g. see http://crbug.com/80157).
      info->response_headers.clear();

      for (void* it = NULL;
           response_headers.EnumerateHeaderLines(&it, &name, &value); ) {
        info->response_headers.push_back(std::make_pair(name, value));
      }
      info->response_headers_text =
          net::HttpUtil::ConvertHeadersBackToHTTPResponse(
              response_headers.raw_headers());
      break;
    }
    case net::NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_JOB: {
      uint32 http_stream_job_id = static_cast<net::NetLogSourceParameter*>(
          params)->value().id;
      HTTPStreamJobToSocketMap::iterator it =
          http_stream_job_to_socket_.find(http_stream_job_id);
      if (it == http_stream_job_to_socket_.end())
        return;
      uint32 socket_id = it->second;

      if (socket_to_request_.size() > kMaxNumEntries) {
        LOG(WARNING) << "The url request observer socket count has grown "
                        "larger than expected, resetting";
        socket_to_request_.clear();
      }

      socket_to_request_[socket_id] = source.id;
      http_stream_job_to_socket_.erase(http_stream_job_id);
      break;
    }
    default:
      break;
  }
}

void DevToolsNetLogObserver::OnAddHTTPStreamJobEntry(
    net::NetLog::EventType type,
    const base::TimeTicks& time,
    const net::NetLog::Source& source,
    net::NetLog::EventPhase phase,
    net::NetLog::EventParameters* params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (type == net::NetLog::TYPE_SOCKET_POOL_BOUND_TO_SOCKET) {
    uint32 socket_id = static_cast<net::NetLogSourceParameter*>(
      params)->value().id;

    // Prevents us from passively growing the memory unbounded in
    // case something went wrong. Should not happen.
    if (http_stream_job_to_socket_.size() > kMaxNumEntries) {
      LOG(WARNING) << "The load timing observer http stream job count "
                      "has grown larger than expected, resetting";
      http_stream_job_to_socket_.clear();
    }
    http_stream_job_to_socket_[source.id] = socket_id;
  }
}

void DevToolsNetLogObserver::OnAddSocketEntry(
    net::NetLog::EventType type,
    const base::TimeTicks& time,
    const net::NetLog::Source& source,
    net::NetLog::EventPhase phase,
    net::NetLog::EventParameters* params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  bool is_end = phase == net::NetLog::PHASE_END;

  SocketToRequestMap::iterator it = socket_to_request_.find(source.id);
  if (it == socket_to_request_.end())
    return;
  uint32 request_id = it->second;

  if (type == net::NetLog::TYPE_SOCKET_IN_USE) {
    if (is_end)
      socket_to_request_.erase(source.id);
    return;
  }

  RequestToEncodedDataLengthMap::iterator encoded_data_length_it =
      request_to_encoded_data_length_.find(request_id);
  if (encoded_data_length_it == request_to_encoded_data_length_.end())
    return;

  if (net::NetLog::TYPE_SOCKET_BYTES_RECEIVED == type) {
    int byte_count = 0;
    scoped_ptr<Value> value(params->ToValue());
    if (!value->IsType(Value::TYPE_DICTIONARY))
      return;

    DictionaryValue* dValue = static_cast<DictionaryValue*>(value.get());
    if (!dValue->GetInteger("byte_count", &byte_count))
      return;

    encoded_data_length_it->second += byte_count;
  }
}

void DevToolsNetLogObserver::Attach(IOThread* io_thread) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!instance_);

  instance_ = new DevToolsNetLogObserver(io_thread->net_log());
}

void DevToolsNetLogObserver::Detach() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(instance_);

  delete instance_;
  instance_ = NULL;
}

DevToolsNetLogObserver* DevToolsNetLogObserver::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  return instance_;
}

// static
void DevToolsNetLogObserver::PopulateResponseInfo(net::URLRequest* request,
                                                  ResourceResponse* response) {
  if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))
    return;

  uint32 source_id = request->net_log().source().id;
  DevToolsNetLogObserver* dev_tools_net_log_observer =
      DevToolsNetLogObserver::GetInstance();
  if (dev_tools_net_log_observer == NULL)
    return;
  response->response_head.devtools_info =
      dev_tools_net_log_observer->GetResourceInfo(source_id);
}

// static
int DevToolsNetLogObserver::GetAndResetEncodedDataLength(
    net::URLRequest* request) {
  if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))
    return -1;

  uint32 source_id = request->net_log().source().id;
  DevToolsNetLogObserver* dev_tools_net_log_observer =
      DevToolsNetLogObserver::GetInstance();
  if (dev_tools_net_log_observer == NULL)
    return -1;

  RequestToEncodedDataLengthMap::iterator it =
      dev_tools_net_log_observer->request_to_encoded_data_length_.find(
          source_id);
  if (it == dev_tools_net_log_observer->request_to_encoded_data_length_.end())
    return -1;
  int encoded_data_length = it->second;
  it->second = 0;
  return encoded_data_length;
}
<|endoftext|>


<commit_before><commit_msg>DevTools: temporarily disable completion test which fails on Linux<commit_after><|endoftext|>


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

#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::wstring& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::wstring& test_page) {
    HTTPTestServer* server = StartHTTPServer();
    GURL url = server->TestServerPageW(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    TabContents* tab = browser()->GetTabContentsAt(0);
    inspected_rvh_ = tab->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
    BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
  RunTest("testHostIsPresent", kSimplePage);
}

// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
  RunTest("testElementsTreeRoot", kSimplePage);
}

// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
  RunTest("testMainResource", kSimplePage);
}

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests profiler panel.
// Flaky, http://crbug.com/21108
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
  RunTest("testSetBreakpoint", kDebuggerTestPage);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
  RunTest("testConsoleEval", kConsoleTestPage);
}

// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
  RunTest("testConsoleLog", kConsoleTestPage);
}

// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
  RunTest("testEvalGlobal", kEvalTestPage);
}

// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
  RunTest("testEvalCallFrame", kEvalTestPage);
}

}  // namespace
<commit_msg>DevTools: re-enable some devtools interactive ui tests that started to fail after WebKit roll.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::wstring& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::wstring& test_page) {
    HTTPTestServer* server = StartHTTPServer();
    GURL url = server->TestServerPageW(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    TabContents* tab = browser()->GetTabContentsAt(0);
    inspected_rvh_ = tab->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
    BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
  RunTest("testHostIsPresent", kSimplePage);
}

// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
  RunTest("testElementsTreeRoot", kSimplePage);
}

// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
  RunTest("testMainResource", kSimplePage);
}

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests profiler panel.
// Flaky, http://crbug.com/21108
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
  RunTest("testSetBreakpoint", kDebuggerTestPage);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
  RunTest("testConsoleEval", kConsoleTestPage);
}

// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
  RunTest("testConsoleLog", kConsoleTestPage);
}

// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
  RunTest("testEvalGlobal", kEvalTestPage);
}

// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
  RunTest("testEvalCallFrame", kEvalTestPage);
}

}  // namespace
<|endoftext|>


<commit_before><commit_msg>DevTools: check that devtools front-end JS files are loaded before running a test, otherwise the test will hang waiting for reponse from the front-end. Review URL: http://codereview.chromium.org/151143<commit_after><|endoftext|>


<commit_before><commit_msg>Rollback 23350. Fix build breakage: no object file generated. TBR=mnaganov<commit_after><|endoftext|>


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

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
// Marked as disabled: crbug/73289.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       DISABLED_TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

}  // namespace
<commit_msg>Enable back DevToolsSanityTest.TestScriptsTabIsPopulatedOnInspectedPageRefresh Should pass after the last WK roll (r75275).<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

}  // namespace
<|endoftext|>