<commit_before>#include <iv/unicode.h>
#include <iv/lv5/jsval.h>
#include <iv/lv5/jsstring.h>
#include <iv/lv5/jsobject.h>
#include <iv/lv5/context.h>
#include <iv/lv5/jsarray.h>
#include <iv/lv5/jsvector.h>
#include <iv/lv5/jsstring.h>
#include <iv/lv5/jsstring_builder.h>
namespace iv {
namespace lv5 {

JSString::JSString(Context* ctx, int32_t size)
  : JSCell(radio::STRING, ctx->global_data()->primitive_string_map(), nullptr)
  , size_(size)
  , flags_(0)
  , data_() {
}

JSString::JSString(Context* ctx)
  : JSCell(radio::STRING, ctx->global_data()->primitive_string_map(), nullptr)
  , size_(0)
  , flags_(STRING_SEQ | IS_8BIT)
  , data_() {
}

JSString* JSString::New(Context* ctx, char16_t ch) {
  if (JSString* res = ctx->global_data()->GetSingleString(ch)) {
    return res;
  }
  // TODO(Yusuke Suzuki):
  // Show this error.
  Error::Dummy dummy;
  if (core::character::IsASCII(ch)) {
    const char ascii = ch;
    return new JSSeqString(ctx, true, &ascii, &ascii + 1);
  } else {
    const char16_t utf16 = ch;
    return new JSSeqString(ctx, false, &utf16, &utf16 + 1);
  }
}

JSString* JSString::NewEmpty(Context* ctx) {
  return ctx->global_data()->string_empty();
}

// TODO(Yusuke Suzuki):
// If it is JSConsString, we should attempt to extract string as cons.
// And we should remove this const_cast.
JSString* JSString::Substring(Context* ctx,
                              size_type from,
                              size_type to) const {
  return JSSlicedString::New(
      ctx,
      const_cast<JSString*>(this),
      from, to == npos ? size() : to);
}

JSString::size_type JSString::find(const JSString& target,
                                   size_type index) const {
  if (Is8Bit() == target.Is8Bit()) {
    // same type
    if (Is8Bit()) {
      return view8().find(target.view8(), index);
    } else {
      return view16().find(target.view16(), index);
    }
  } else {
    if (Is8Bit()) {
      core::u16string_view rhs = target.view16();
      return view8().find(rhs.begin(), rhs.end(), index);
    } else {
      core::string_view rhs = target.view8();
      return view16().find(rhs.begin(), rhs.end(), index);
    }
  }
}

JSString::size_type JSString::rfind(const JSString& target,
                                    size_type index) const {
  if (Is8Bit() == target.Is8Bit()) {
    // same type
    if (Is8Bit()) {
      return view8().rfind(target.view8(), index);
    } else {
      return view16().rfind(target.view16(), index);
    }
  } else {
    if (Is8Bit()) {
      core::u16string_view rhs = target.view16();
      return view8().rfind(rhs.begin(), rhs.end(), index);
    } else {
      core::string_view rhs = target.view8();
      return view16().rfind(rhs.begin(), rhs.end(), index);
    }
  }
}

std::string JSString::GetUTF8() const {
  if (Is8Bit()) {
    return view8();
  }
  const core::u16string_view view = view16();
  std::string str;
  str.reserve(size() * 2);
  if (core::unicode::UTF16ToUTF8(
          view.begin(),
          view.end(),
          std::back_inserter(str)) != core::unicode::UNICODE_NO_ERROR) {
    str.clear();
  }
  return str;
}

std::u16string JSString::GetUTF16() const {
  if (Is16Bit()) {
    return view16();
  }
  const core::string_view view = view8();
  std::u16string str;
  str.resize(size());
  std::copy(view.begin(), view.end(), str.begin());
  return str;
}

JSString* JSString::Repeat(Context* ctx, uint32_t count, Error* e) {
  if (count == 0 || empty()) {
    return NewEmpty(ctx);
  }
  if (count == 1) {
    return this;
  }
  JSString* current = this;
  JSString* result = NewEmpty(ctx);
  do {
    if (count & 1) {
      result = JSString::NewCons(ctx, result, current, IV_LV5_ERROR(e));
    }
    count >>= 1;
    current = JSString::NewCons(ctx, current, current, IV_LV5_ERROR(e));
  } while (count > 0);
  return result;
}

std::ostream& operator<<(std::ostream& os, const JSString& str) {
  if (str.Is8Bit()) {
    auto view = str.view8();
    os.write(view.data(), view.size());
  } else {
    auto view = str.view16();
    core::unicode::UTF16ToUTF8(view.begin(),
                               view.end(),
                               std::ostream_iterator<char>(os));
  }
  return os;
}

char16_t JSFlatString::operator[](size_type n) const {
  if (Is8Bit()) {
    return (*As<char>())[n];
  } else {
    return (*As<char16_t>())[n];
  }
}

int JSFlatString::compare(const this_type& x) const {
  if (Is8Bit() == x.Is8Bit()) {
    // same type. use downcast
    if (Is8Bit()) {
      return As<char>()->compare(*x.As<char>());
    } else {
      return As<char16_t>()->compare(*x.As<char16_t>());
    }
  }
  if (Is8Bit()) {
    return core::CompareIterators(
        As<char>()->begin(), As<char>()->end(),
        x.As<char16_t>()->begin(), x.As<char16_t>()->end());
  } else {
    return core::CompareIterators(
        As<char16_t>()->begin(), As<char16_t>()->end(),
        x.As<char>()->begin(), x.As<char>()->end());
  }
}

char16_t JSString::At(size_type n) const {
  assert(n < size());
  const JSString* current = this;
  size_type offset = n;
  do {
    assert(!current->empty());
    if (current->IsFlat()) {
      return (*static_cast<const JSFlatString*>(current))[offset];
    }
    const JSConsString* cons = static_cast<const JSConsString*>(current);
    if (cons->lhs()->size() > offset) {
      current = cons->lhs();
    } else {
      current = cons->rhs();
      offset -= cons->lhs()->size();
    }
  } while (true);
  return 0;  // Makes compiler happy.
}

JSString* JSString::New(Context* ctx, Symbol sym) {
  if (symbol::IsIndexSymbol(sym)) {
    const uint32_t index = symbol::GetIndexFromSymbol(sym);
    if (index < 10) {
      return New(ctx, index + '0');
    }
    std::array<char, 15> buffer;
    char* end = core::UInt32ToString(index, buffer.data());
    Error::Dummy dummy;
    return JSSeqString::New(ctx, buffer.data(), end, true, &dummy);
  } else {
    assert(!symbol::IsIndexSymbol(sym));
    const std::u16string* str = symbol::GetStringFromSymbol(sym);
    if (str->empty()) {
      return NewEmpty(ctx);
    }
    if (str->size() == 1) {
      return New(ctx, (*str)[0]);
    }
    assert(str->size() <= kMaxSize);
    return JSString::NewExternal(ctx, *str);
  }
}

JSString* JSString::NewCons(Context* ctx,
                            JSVal* src,
                            uint32_t count,
                            Error* e) {
  if (count == 0) {
    return NewEmpty(ctx);
  }
  if (count == 1) {
    return src[0].string();
  }
  JSString* cons = JSString::NewCons(ctx,
                                     src[0].string(),
                                     src[1].string(),
                                     IV_LV5_ERROR(e));
  for (uint32_t i = 2; i < count; ++i) {
    cons = JSString::NewCons(ctx, cons, src[i].string(), IV_LV5_ERROR(e));
  }
  return cons;
}

template<typename CharIterator, typename OutputIterator>
inline OutputIterator SplitString(Context* ctx,
                                  CharIterator i,
                                  CharIterator iz,
                                  OutputIterator j) {
  for (; i != iz; ++i, ++j) {
    *j = JSString::New(ctx, *i);
  }
  return j;
}

// "STRING".split("") => ['S', 'T', 'R', 'I', 'N', 'G']
JSArray* JSString::Split(Context* ctx, uint32_t limit, Error* e) const {
  Flatten();
  const uint32_t smaller = (std::min<uint32_t>)(limit, size());
  JSVector* vec = JSVector::New(ctx, smaller);
  if (Is8Bit()) {
    const core::string_view view = view8();
    SplitString(ctx, view.begin(), view.begin() + smaller, vec->begin());
  } else {
    const core::u16string_view view = view16();
    SplitString(ctx, view.begin(), view.begin() + smaller, vec->begin());
  }
  return vec->ToJSArray();
}

JSArray* JSString::Split(Context* ctx,
                         char16_t ch,
                         uint32_t limit,
                         Error* e) const {
  JSVector* vec = JSVector::New(ctx);
  Flatten();
  if (Is8Bit()) {
    if (!core::character::IsASCII(ch)) {
      if (limit != 0) {
        // TODO(Yusuke Suzuki):
        // Remove const_cast.
        vec->push_back(const_cast<JSString*>(this));
      }
      return vec->ToJSArray();
    }
    const core::string_view view = view8();
    std::size_t index = 0;
    for (uint32_t i = 0; i < limit; ++i) {
      const std::size_t pos = view.find(ch, index);
      if (pos == core::string_view::npos) {
        vec->push_back(Substring(ctx, index, size()));
        break;
      }
      vec->push_back(Substring(ctx, index, pos));
      index = pos + 1;
    }
  } else {
    const core::u16string_view view = view16();
    std::size_t index = 0;
    for (uint32_t i = 0; i < limit; ++i) {
      const std::size_t pos = view.find(ch, index);
      if (pos == core::u16string_view::npos) {
        vec->push_back(Substring(ctx, index, size()));
        break;
      }
      vec->push_back(Substring(ctx, index, pos));
      index = pos + 1;
    }
  }
  return vec->ToJSArray();
}

} }  // namespace iv::lv5
<commit_msg>Quickly give up picking n's character from String when String is not flat.<commit_after>#include <iv/unicode.h>
#include <iv/lv5/jsval.h>
#include <iv/lv5/jsstring.h>
#include <iv/lv5/jsobject.h>
#include <iv/lv5/context.h>
#include <iv/lv5/jsarray.h>
#include <iv/lv5/jsvector.h>
#include <iv/lv5/jsstring.h>
#include <iv/lv5/jsstring_builder.h>
namespace iv {
namespace lv5 {

JSString::JSString(Context* ctx, int32_t size)
  : JSCell(radio::STRING, ctx->global_data()->primitive_string_map(), nullptr)
  , size_(size)
  , flags_(0)
  , data_() {
}

JSString::JSString(Context* ctx)
  : JSCell(radio::STRING, ctx->global_data()->primitive_string_map(), nullptr)
  , size_(0)
  , flags_(STRING_SEQ | IS_8BIT)
  , data_() {
}

JSString* JSString::New(Context* ctx, char16_t ch) {
  if (JSString* res = ctx->global_data()->GetSingleString(ch)) {
    return res;
  }
  // TODO(Yusuke Suzuki):
  // Show this error.
  Error::Dummy dummy;
  if (core::character::IsASCII(ch)) {
    const char ascii = ch;
    return new JSSeqString(ctx, true, &ascii, &ascii + 1);
  } else {
    const char16_t utf16 = ch;
    return new JSSeqString(ctx, false, &utf16, &utf16 + 1);
  }
}

JSString* JSString::NewEmpty(Context* ctx) {
  return ctx->global_data()->string_empty();
}

// TODO(Yusuke Suzuki):
// If it is JSConsString, we should attempt to extract string as cons.
// And we should remove this const_cast.
JSString* JSString::Substring(Context* ctx,
                              size_type from,
                              size_type to) const {
  return JSSlicedString::New(
      ctx,
      const_cast<JSString*>(this),
      from, to == npos ? size() : to);
}

JSString::size_type JSString::find(const JSString& target,
                                   size_type index) const {
  if (Is8Bit() == target.Is8Bit()) {
    // same type
    if (Is8Bit()) {
      return view8().find(target.view8(), index);
    } else {
      return view16().find(target.view16(), index);
    }
  } else {
    if (Is8Bit()) {
      core::u16string_view rhs = target.view16();
      return view8().find(rhs.begin(), rhs.end(), index);
    } else {
      core::string_view rhs = target.view8();
      return view16().find(rhs.begin(), rhs.end(), index);
    }
  }
}

JSString::size_type JSString::rfind(const JSString& target,
                                    size_type index) const {
  if (Is8Bit() == target.Is8Bit()) {
    // same type
    if (Is8Bit()) {
      return view8().rfind(target.view8(), index);
    } else {
      return view16().rfind(target.view16(), index);
    }
  } else {
    if (Is8Bit()) {
      core::u16string_view rhs = target.view16();
      return view8().rfind(rhs.begin(), rhs.end(), index);
    } else {
      core::string_view rhs = target.view8();
      return view16().rfind(rhs.begin(), rhs.end(), index);
    }
  }
}

std::string JSString::GetUTF8() const {
  if (Is8Bit()) {
    return view8();
  }
  const core::u16string_view view = view16();
  std::string str;
  str.reserve(size() * 2);
  if (core::unicode::UTF16ToUTF8(
          view.begin(),
          view.end(),
          std::back_inserter(str)) != core::unicode::UNICODE_NO_ERROR) {
    str.clear();
  }
  return str;
}

std::u16string JSString::GetUTF16() const {
  if (Is16Bit()) {
    return view16();
  }
  const core::string_view view = view8();
  std::u16string str;
  str.resize(size());
  std::copy(view.begin(), view.end(), str.begin());
  return str;
}

JSString* JSString::Repeat(Context* ctx, uint32_t count, Error* e) {
  if (count == 0 || empty()) {
    return NewEmpty(ctx);
  }
  if (count == 1) {
    return this;
  }
  JSString* current = this;
  JSString* result = NewEmpty(ctx);
  do {
    if (count & 1) {
      result = JSString::NewCons(ctx, result, current, IV_LV5_ERROR(e));
    }
    count >>= 1;
    current = JSString::NewCons(ctx, current, current, IV_LV5_ERROR(e));
  } while (count > 0);
  return result;
}

std::ostream& operator<<(std::ostream& os, const JSString& str) {
  if (str.Is8Bit()) {
    auto view = str.view8();
    os.write(view.data(), view.size());
  } else {
    auto view = str.view16();
    core::unicode::UTF16ToUTF8(view.begin(),
                               view.end(),
                               std::ostream_iterator<char>(os));
  }
  return os;
}

char16_t JSFlatString::operator[](size_type n) const {
  if (Is8Bit()) {
    return (*As<char>())[n];
  } else {
    return (*As<char16_t>())[n];
  }
}

int JSFlatString::compare(const this_type& x) const {
  if (Is8Bit() == x.Is8Bit()) {
    // same type. use downcast
    if (Is8Bit()) {
      return As<char>()->compare(*x.As<char>());
    } else {
      return As<char16_t>()->compare(*x.As<char16_t>());
    }
  }
  if (Is8Bit()) {
    return core::CompareIterators(
        As<char>()->begin(), As<char>()->end(),
        x.As<char16_t>()->begin(), x.As<char16_t>()->end());
  } else {
    return core::CompareIterators(
        As<char16_t>()->begin(), As<char16_t>()->end(),
        x.As<char>()->begin(), x.As<char>()->end());
  }
}

char16_t JSString::At(size_type n) const {
  assert(n < size());
  if (IsFlat()) {
    return (*static_cast<const JSFlatString*>(this))[n];
  }
  Flatten();
  return (*static_cast<const JSFlatString*>(this))[n];
}

JSString* JSString::New(Context* ctx, Symbol sym) {
  if (symbol::IsIndexSymbol(sym)) {
    const uint32_t index = symbol::GetIndexFromSymbol(sym);
    if (index < 10) {
      return New(ctx, index + '0');
    }
    std::array<char, 15> buffer;
    char* end = core::UInt32ToString(index, buffer.data());
    Error::Dummy dummy;
    return JSSeqString::New(ctx, buffer.data(), end, true, &dummy);
  } else {
    assert(!symbol::IsIndexSymbol(sym));
    const std::u16string* str = symbol::GetStringFromSymbol(sym);
    if (str->empty()) {
      return NewEmpty(ctx);
    }
    if (str->size() == 1) {
      return New(ctx, (*str)[0]);
    }
    assert(str->size() <= kMaxSize);
    return JSString::NewExternal(ctx, *str);
  }
}

JSString* JSString::NewCons(Context* ctx,
                            JSVal* src,
                            uint32_t count,
                            Error* e) {
  if (count == 0) {
    return NewEmpty(ctx);
  }
  if (count == 1) {
    return src[0].string();
  }
  JSString* cons = JSString::NewCons(ctx,
                                     src[0].string(),
                                     src[1].string(),
                                     IV_LV5_ERROR(e));
  for (uint32_t i = 2; i < count; ++i) {
    cons = JSString::NewCons(ctx, cons, src[i].string(), IV_LV5_ERROR(e));
  }
  return cons;
}

template<typename CharIterator, typename OutputIterator>
inline OutputIterator SplitString(Context* ctx,
                                  CharIterator i,
                                  CharIterator iz,
                                  OutputIterator j) {
  for (; i != iz; ++i, ++j) {
    *j = JSString::New(ctx, *i);
  }
  return j;
}

// "STRING".split("") => ['S', 'T', 'R', 'I', 'N', 'G']
JSArray* JSString::Split(Context* ctx, uint32_t limit, Error* e) const {
  Flatten();
  const uint32_t smaller = (std::min<uint32_t>)(limit, size());
  JSVector* vec = JSVector::New(ctx, smaller);
  if (Is8Bit()) {
    const core::string_view view = view8();
    SplitString(ctx, view.begin(), view.begin() + smaller, vec->begin());
  } else {
    const core::u16string_view view = view16();
    SplitString(ctx, view.begin(), view.begin() + smaller, vec->begin());
  }
  return vec->ToJSArray();
}

JSArray* JSString::Split(Context* ctx,
                         char16_t ch,
                         uint32_t limit,
                         Error* e) const {
  JSVector* vec = JSVector::New(ctx);
  Flatten();
  if (Is8Bit()) {
    if (!core::character::IsASCII(ch)) {
      if (limit != 0) {
        // TODO(Yusuke Suzuki):
        // Remove const_cast.
        vec->push_back(const_cast<JSString*>(this));
      }
      return vec->ToJSArray();
    }
    const core::string_view view = view8();
    std::size_t index = 0;
    for (uint32_t i = 0; i < limit; ++i) {
      const std::size_t pos = view.find(ch, index);
      if (pos == core::string_view::npos) {
        vec->push_back(Substring(ctx, index, size()));
        break;
      }
      vec->push_back(Substring(ctx, index, pos));
      index = pos + 1;
    }
  } else {
    const core::u16string_view view = view16();
    std::size_t index = 0;
    for (uint32_t i = 0; i < limit; ++i) {
      const std::size_t pos = view.find(ch, index);
      if (pos == core::u16string_view::npos) {
        vec->push_back(Substring(ctx, index, size()));
        break;
      }
      vec->push_back(Substring(ctx, index, pos));
      index = pos + 1;
    }
  }
  return vec->ToJSArray();
}

} }  // namespace iv::lv5
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkGEImageIOTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <string>
#include "itkGEAdwImageIO.h"
#include "itkGE4ImageIO.h"
#include "itkGE5ImageIO.h"
#include "itkSiemensVisionImageIO.h"
#include "itkGEAdwImageIOFactory.h"
#include "itkGE4ImageIOFactory.h"
#include "itkGE5ImageIOFactory.h"
#include "itkSiemensVisionImageIOFactory.h"
#include "itkImageIOFactory.h"
#include "itkExceptionObject.h"
#include "itkImageFileReader.h"
#include "itkImage.h"
#include <itksys/SystemTools.hxx>

typedef itk::Image<signed short, 3> ImageType ;
typedef ImageType::Pointer ImagePointer ;
typedef itk::ImageFileReader< ImageType > ImageReaderType ;

int itkGEImageIOFactoryTest(int ac, char * av[])
{
  static bool firstTime = true;
  if(firstTime)
    {
    itk::ObjectFactoryBase::RegisterFactory(itk::GEAdwImageIOFactory::New() );
    itk::ObjectFactoryBase::RegisterFactory(itk::GE4ImageIOFactory::New() );
    itk::ObjectFactoryBase::RegisterFactory(itk::GE5ImageIOFactory::New() );
    itk::ObjectFactoryBase::RegisterFactory(itk::SiemensVisionImageIOFactory::New() );
    firstTime = false;
    }
  if(ac < 2)
    {
    return 1;
    }
  char *filename = *++av;

  ImagePointer input ;
  ImageReaderType::Pointer imageReader = ImageReaderType::New() ;

  try
    {
    imageReader->SetFileName(filename);
    imageReader->Update() ;
    input = imageReader->GetOutput() ;
    }
  catch (itk::ExceptionObject e)
    {
    return 1;
    }
  return 0;
}

int itkGEImageIOTest(int ac, char * av[])
{
  //
  // first argument is passing in the writable directory to do all testing
  if(ac > 1) {
    char *testdir = *++av;
    --ac;
    itksys::SystemTools::ChangeDirectory(testdir);
  }
  if(ac != 4)
    return 1;
  std::string failmode(av[1]);
  std::string filetype(av[2]);
  std::string filename(av[3]);
  bool Failmode = failmode == std::string("true");
  itk::ImageIOBase::Pointer io;
  if(filetype == "GE4")
    {
      io = itk::GE4ImageIO::New();
    }
  else if(filetype == "GE5")
    {
      io = itk::GE5ImageIO::New();
    }
  else if(filetype == "GEAdw")
    {
      io = itk::GEAdwImageIO::New();
    }
  else if(filetype == "Siemens")
    {
      io = itk::SiemensVisionImageIO::New();
    }
  else
    {
      return 1;
    }

  ImagePointer input ;
  ImageReaderType::Pointer imageReader = ImageReaderType::New() ;

  try
    {
      imageReader->SetImageIO(io);
      imageReader->SetFileName(filename.c_str()) ;
      imageReader->Update() ;
      input = imageReader->GetOutput() ;
    }
  catch (itk::ExceptionObject e)
    {
      return Failmode ? 1 : 0;
    }
  return Failmode ? 0 : 1;
}

<commit_msg>BUG: Exceptions that are caught should be displayed.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkGEImageIOTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <string>
#include "itkGEAdwImageIO.h"
#include "itkGE4ImageIO.h"
#include "itkGE5ImageIO.h"
#include "itkSiemensVisionImageIO.h"
#include "itkGEAdwImageIOFactory.h"
#include "itkGE4ImageIOFactory.h"
#include "itkGE5ImageIOFactory.h"
#include "itkSiemensVisionImageIOFactory.h"
#include "itkImageIOFactory.h"
#include "itkExceptionObject.h"
#include "itkImageFileReader.h"
#include "itkImage.h"
#include <itksys/SystemTools.hxx>

typedef itk::Image<signed short, 3> ImageType ;
typedef ImageType::Pointer ImagePointer ;
typedef itk::ImageFileReader< ImageType > ImageReaderType ;

int itkGEImageIOFactoryTest(int ac, char * av[])
{
  static bool firstTime = true;
  if(firstTime)
    {
    itk::ObjectFactoryBase::RegisterFactory(itk::GEAdwImageIOFactory::New() );
    itk::ObjectFactoryBase::RegisterFactory(itk::GE4ImageIOFactory::New() );
    itk::ObjectFactoryBase::RegisterFactory(itk::GE5ImageIOFactory::New() );
    itk::ObjectFactoryBase::RegisterFactory(itk::SiemensVisionImageIOFactory::New() );
    firstTime = false;
    }
  if(ac < 2)
    {
    return 1;
    }
  char *filename = *++av;

  ImagePointer input ;
  ImageReaderType::Pointer imageReader = ImageReaderType::New() ;

  try
    {
    imageReader->SetFileName(filename);
    imageReader->Update() ;
    input = imageReader->GetOutput() ;
    }
  catch (itk::ExceptionObject e)
    {
    std::cerr << "itkGEImageIOFactoryTest caught an exception:\n"
              << e.what() << std::endl;
    return 1;
    }
  return 0;
}

int itkGEImageIOTest(int ac, char * av[])
{
  //
  // first argument is passing in the writable directory to do all testing
  if(ac > 1) {
    char *testdir = *++av;
    --ac;
    itksys::SystemTools::ChangeDirectory(testdir);
  }
  if(ac != 4)
    return 1;
  std::string failmode(av[1]);
  std::string filetype(av[2]);
  std::string filename(av[3]);
  bool Failmode = failmode == std::string("true");
  itk::ImageIOBase::Pointer io;
  if(filetype == "GE4")
    {
      io = itk::GE4ImageIO::New();
    }
  else if(filetype == "GE5")
    {
      io = itk::GE5ImageIO::New();
    }
  else if(filetype == "GEAdw")
    {
      io = itk::GEAdwImageIO::New();
    }
  else if(filetype == "Siemens")
    {
      io = itk::SiemensVisionImageIO::New();
    }
  else
    {
      return 1;
    }

  ImagePointer input ;
  ImageReaderType::Pointer imageReader = ImageReaderType::New() ;

  try
    {
      imageReader->SetImageIO(io);
      imageReader->SetFileName(filename.c_str()) ;
      imageReader->Update() ;
      input = imageReader->GetOutput() ;
    }
  catch (itk::ExceptionObject e)
    {
    std::cerr << "itkGEImageIOTest caught an exception:\n"
              << e.what() << std::endl;
    return Failmode ? 1 : 0;
    }
  return Failmode ? 0 : 1;
}

<|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 "chrome/browser/chromeos/status_area_button.h"

#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false) {
  set_border(NULL);
  SetShowHighlighted(true);
}

void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
  int bitmap_id;

  switch(state()) {
    case BS_NORMAL:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      break;
    case BS_HOT:
      bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
      break;
    case BS_PUSHED:
      bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
      break;
    default:
      NOTREACHED();
  }
  SkBitmap* container =
      ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
  canvas->DrawBitmapInt(*container, 0, 0);
  canvas->DrawBitmapInt(icon(), 0, 0);
}
<commit_msg>Fix for Release build break<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 "chrome/browser/chromeos/status_area_button.h"

#include "app/gfx/canvas.h"
#include "app/gfx/skbitmap_operations.h"
#include "app/resource_bundle.h"
#include "grit/theme_resources.h"
#include "views/border.h"
#include "views/view.h"

////////////////////////////////////////////////////////////////////////////////
// StatusAreaButton

StatusAreaButton::StatusAreaButton(views::ViewMenuDelegate* menu_delegate)
    : MenuButton(NULL, std::wstring(), menu_delegate, false) {
  set_border(NULL);
  SetShowHighlighted(true);
}

void StatusAreaButton::Paint(gfx::Canvas* canvas, bool for_drag) {
  int bitmap_id;

  switch(state()) {
    case BS_NORMAL:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      break;
    case BS_HOT:
      bitmap_id = IDR_STATUSBAR_CONTAINER_HOVER;
      break;
    case BS_PUSHED:
      bitmap_id = IDR_STATUSBAR_CONTAINER_PRESSED;
      break;
    default:
      bitmap_id = IDR_STATUSBAR_CONTAINER;
      NOTREACHED();
  }
  SkBitmap* container =
      ResourceBundle::GetSharedInstance().GetBitmapNamed(bitmap_id);
  canvas->DrawBitmapInt(*container, 0, 0);
  canvas->DrawBitmapInt(icon(), 0, 0);
}
<|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 "chrome/browser/content_setting_image_model.h"

#include "base/command_line.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"

class ContentSettingBlockedImageModel : public ContentSettingImageModel {
 public:
  explicit ContentSettingBlockedImageModel(
      ContentSettingsType content_settings_type);

  virtual void UpdateFromTabContents(TabContents* tab_contents);

 private:
  static const int kAccessedIconIDs[];
  static const int kBlockedIconIDs[];
  static const int kBlockedExplanatoryTextIDs[];
  static const int kAccessedExplanatoryTextIDs[];
  static const int kAccessedTooltipIDs[];
  static const int kBlockedTooltipIDs[];
};

class ContentSettingGeolocationImageModel : public ContentSettingImageModel {
 public:
  ContentSettingGeolocationImageModel();

  virtual void UpdateFromTabContents(TabContents* tab_contents);
};

class ContentSettingNotificationsImageModel : public ContentSettingImageModel {
 public:
  ContentSettingNotificationsImageModel();

  virtual void UpdateFromTabContents(TabContents* tab_contents);
};

const int ContentSettingBlockedImageModel::kBlockedIconIDs[] = {
    IDR_BLOCKED_COOKIES,
    IDR_BLOCKED_IMAGES,
    IDR_BLOCKED_JAVASCRIPT,
    IDR_BLOCKED_PLUGINS,
    IDR_BLOCKED_POPUPS,
};

const int ContentSettingBlockedImageModel::kAccessedIconIDs[] = {
    IDR_ACCESSED_COOKIES,
    0,
    0,
    0,
    0,
};

const int ContentSettingBlockedImageModel::kBlockedExplanatoryTextIDs[] = {
    0,
    0,
    0,
    0,
    IDS_BLOCKED_POPUPS_EXPLANATORY_TEXT,
};

const int ContentSettingBlockedImageModel::kAccessedExplanatoryTextIDs[] = {
    0,
    0,
    0,
    0,
    0,
};

const int ContentSettingBlockedImageModel::kBlockedTooltipIDs[] = {
    IDS_BLOCKED_COOKIES_TITLE,
    IDS_BLOCKED_IMAGES_TITLE,
    IDS_BLOCKED_JAVASCRIPT_TITLE,
    IDS_BLOCKED_PLUGINS_MESSAGE,
    IDS_BLOCKED_POPUPS_TOOLTIP,
};

const int ContentSettingBlockedImageModel::kAccessedTooltipIDs[] = {
    IDS_ACCESSED_COOKIES_TITLE,
    0,
    0,
    0,
    0,
};

ContentSettingBlockedImageModel::ContentSettingBlockedImageModel(
    ContentSettingsType content_settings_type)
    : ContentSettingImageModel(content_settings_type) {
}

void ContentSettingBlockedImageModel::UpdateFromTabContents(
    TabContents* tab_contents) {
  TabSpecificContentSettings* content_settings = tab_contents ?
      tab_contents->GetTabSpecificContentSettings() : NULL;
  const int* icon_ids;
  const int* tooltip_ids;
  const int* explanatory_string_ids;

  if (!content_settings) {
    set_visible(false);
    return;
  }
  if (content_settings->IsContentBlocked(get_content_settings_type())) {
    icon_ids = kBlockedIconIDs;
    tooltip_ids = kBlockedTooltipIDs;
    explanatory_string_ids = kBlockedExplanatoryTextIDs;
  } else if (tab_contents->profile()->GetHostContentSettingsMap()->
                 GetDefaultContentSetting(get_content_settings_type()) ==
                 CONTENT_SETTING_BLOCK &&
             content_settings->IsContentAccessed(get_content_settings_type())) {
    // If a content type is blocked by default and was accessed, display the
    // accessed icon.
    icon_ids = kAccessedIconIDs;
    tooltip_ids = kAccessedTooltipIDs;
    explanatory_string_ids = kAccessedExplanatoryTextIDs;
  } else {
    set_visible(false);
    return;
  }
  set_icon(icon_ids[get_content_settings_type()]);
  set_explanatory_string_id(
      explanatory_string_ids[get_content_settings_type()]);
  set_tooltip(
      l10n_util::GetStringUTF8(tooltip_ids[get_content_settings_type()]));
  set_visible(true);
}

ContentSettingGeolocationImageModel::ContentSettingGeolocationImageModel()
    : ContentSettingImageModel(CONTENT_SETTINGS_TYPE_GEOLOCATION) {
}

void ContentSettingGeolocationImageModel::UpdateFromTabContents(
    TabContents* tab_contents) {
  if (!tab_contents) {
    set_visible(false);
    return;
  }
  TabSpecificContentSettings* content_settings =
      tab_contents->GetTabSpecificContentSettings();
  const GeolocationSettingsState& settings_state =
      content_settings->geolocation_settings_state();
  if (settings_state.state_map().empty()) {
    set_visible(false);
    return;
  }
  set_visible(true);
  unsigned int tab_state_flags = 0;
  settings_state.GetDetailedInfo(NULL, &tab_state_flags);
  // If any embedded site has access the allowed icon takes priority over the
  // blocked icon.
  if (tab_state_flags & GeolocationSettingsState::TABSTATE_HAS_ANY_ALLOWED) {
    set_icon(IDR_GEOLOCATION_ALLOWED_LOCATIONBAR_ICON);
    set_tooltip(l10n_util::GetStringUTF8(IDS_GEOLOCATION_ALLOWED_TOOLTIP));
    return;
  }
  set_icon(IDR_GEOLOCATION_DENIED_LOCATIONBAR_ICON);
  set_tooltip(l10n_util::GetStringUTF8(IDS_GEOLOCATION_BLOCKED_TOOLTIP));
}

ContentSettingNotificationsImageModel::ContentSettingNotificationsImageModel()
    : ContentSettingImageModel(CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
}

void ContentSettingNotificationsImageModel::UpdateFromTabContents(
    TabContents* tab_contents) {
  // Notifications do not have a bubble.
  set_visible(false);
}

ContentSettingImageModel::ContentSettingImageModel(
    ContentSettingsType content_settings_type)
    : content_settings_type_(content_settings_type),
      is_visible_(false),
      icon_(0),
      explanatory_string_id_(0) {
}

// static
ContentSettingImageModel*
    ContentSettingImageModel::CreateContentSettingImageModel(
    ContentSettingsType content_settings_type) {
  if (content_settings_type == CONTENT_SETTINGS_TYPE_GEOLOCATION)
    return new ContentSettingGeolocationImageModel();
  if (content_settings_type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return new ContentSettingNotificationsImageModel();
  return new ContentSettingBlockedImageModel(content_settings_type);
}
<commit_msg>Cleanup: shorten.<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 "chrome/browser/content_setting_image_model.h"

#include "base/command_line.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"

class ContentSettingBlockedImageModel : public ContentSettingImageModel {
 public:
  explicit ContentSettingBlockedImageModel(
      ContentSettingsType content_settings_type);

  virtual void UpdateFromTabContents(TabContents* tab_contents);

 private:
  static const int kAccessedIconIDs[];
  static const int kBlockedIconIDs[];
  static const int kBlockedExplanatoryTextIDs[];
  static const int kAccessedExplanatoryTextIDs[];
  static const int kAccessedTooltipIDs[];
  static const int kBlockedTooltipIDs[];
};

class ContentSettingGeolocationImageModel : public ContentSettingImageModel {
 public:
  ContentSettingGeolocationImageModel();

  virtual void UpdateFromTabContents(TabContents* tab_contents);
};

class ContentSettingNotificationsImageModel : public ContentSettingImageModel {
 public:
  ContentSettingNotificationsImageModel();

  virtual void UpdateFromTabContents(TabContents* tab_contents);
};

const int ContentSettingBlockedImageModel::kBlockedIconIDs[] = {
    IDR_BLOCKED_COOKIES,
    IDR_BLOCKED_IMAGES,
    IDR_BLOCKED_JAVASCRIPT,
    IDR_BLOCKED_PLUGINS,
    IDR_BLOCKED_POPUPS,
};

const int ContentSettingBlockedImageModel::kAccessedIconIDs[] = {
    IDR_ACCESSED_COOKIES,
    0,
    0,
    0,
    0,
};

const int ContentSettingBlockedImageModel::kBlockedExplanatoryTextIDs[] = {
    0,
    0,
    0,
    0,
    IDS_BLOCKED_POPUPS_EXPLANATORY_TEXT,
};

const int ContentSettingBlockedImageModel::kAccessedExplanatoryTextIDs[] = {
    0,
    0,
    0,
    0,
    0,
};

const int ContentSettingBlockedImageModel::kBlockedTooltipIDs[] = {
    IDS_BLOCKED_COOKIES_TITLE,
    IDS_BLOCKED_IMAGES_TITLE,
    IDS_BLOCKED_JAVASCRIPT_TITLE,
    IDS_BLOCKED_PLUGINS_MESSAGE,
    IDS_BLOCKED_POPUPS_TOOLTIP,
};

const int ContentSettingBlockedImageModel::kAccessedTooltipIDs[] = {
    IDS_ACCESSED_COOKIES_TITLE,
    0,
    0,
    0,
    0,
};

ContentSettingBlockedImageModel::ContentSettingBlockedImageModel(
    ContentSettingsType content_settings_type)
    : ContentSettingImageModel(content_settings_type) {
}

void ContentSettingBlockedImageModel::UpdateFromTabContents(
    TabContents* tab_contents) {
  set_visible(false);
  if (!tab_contents)
    return;

  const int* icon_ids = kBlockedIconIDs;
  const int* tooltip_ids = kBlockedTooltipIDs;
  const int* explanatory_string_ids = kBlockedExplanatoryTextIDs;
  // If a content type is blocked by default and was accessed, display the
  // accessed icon.
  TabSpecificContentSettings* content_settings =
      tab_contents->GetTabSpecificContentSettings();
  if (!content_settings->IsContentBlocked(get_content_settings_type())) {
    if (!content_settings->IsContentAccessed(get_content_settings_type()) ||
        (tab_contents->profile()->GetHostContentSettingsMap()->
            GetDefaultContentSetting(get_content_settings_type()) !=
                CONTENT_SETTING_BLOCK))
      return;
    icon_ids = kAccessedIconIDs;
    tooltip_ids = kAccessedTooltipIDs;
    explanatory_string_ids = kAccessedExplanatoryTextIDs;
  }
  set_visible(true);
  set_icon(icon_ids[get_content_settings_type()]);
  set_explanatory_string_id(
      explanatory_string_ids[get_content_settings_type()]);
  set_tooltip(
      l10n_util::GetStringUTF8(tooltip_ids[get_content_settings_type()]));
}

ContentSettingGeolocationImageModel::ContentSettingGeolocationImageModel()
    : ContentSettingImageModel(CONTENT_SETTINGS_TYPE_GEOLOCATION) {
}

void ContentSettingGeolocationImageModel::UpdateFromTabContents(
    TabContents* tab_contents) {
  set_visible(false);
  if (!tab_contents)
    return;
  const GeolocationSettingsState& settings_state = tab_contents->
      GetTabSpecificContentSettings()->geolocation_settings_state();
  if (settings_state.state_map().empty())
    return;
  set_visible(true);

  // If any embedded site has access the allowed icon takes priority over the
  // blocked icon.
  unsigned int tab_state_flags = 0;
  settings_state.GetDetailedInfo(NULL, &tab_state_flags);
  bool allowed =
      !!(tab_state_flags & GeolocationSettingsState::TABSTATE_HAS_ANY_ALLOWED);
  set_icon(allowed ? IDR_GEOLOCATION_ALLOWED_LOCATIONBAR_ICON :
      IDR_GEOLOCATION_DENIED_LOCATIONBAR_ICON);
  set_tooltip(l10n_util::GetStringUTF8(allowed ?
      IDS_GEOLOCATION_ALLOWED_TOOLTIP : IDS_GEOLOCATION_BLOCKED_TOOLTIP));
}

ContentSettingNotificationsImageModel::ContentSettingNotificationsImageModel()
    : ContentSettingImageModel(CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
}

void ContentSettingNotificationsImageModel::UpdateFromTabContents(
    TabContents* tab_contents) {
  // Notifications do not have a bubble.
  set_visible(false);
}

ContentSettingImageModel::ContentSettingImageModel(
    ContentSettingsType content_settings_type)
    : content_settings_type_(content_settings_type),
      is_visible_(false),
      icon_(0),
      explanatory_string_id_(0) {
}

// static
ContentSettingImageModel*
    ContentSettingImageModel::CreateContentSettingImageModel(
    ContentSettingsType content_settings_type) {
  if (content_settings_type == CONTENT_SETTINGS_TYPE_GEOLOCATION)
    return new ContentSettingGeolocationImageModel();
  if (content_settings_type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return new ContentSettingNotificationsImageModel();
  return new ContentSettingBlockedImageModel(content_settings_type);
}
<|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 "chrome/browser/dom_ui/app_launcher_handler.h"

#include "app/resource_bundle.h"
#include "base/base64.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/browser_resources.h"

namespace {

bool TreatAsApp(const Extension* extension) {
  return !extension->GetFullLaunchURL().is_empty();
}

}  // namespace

AppLauncherHandler::AppLauncherHandler(
    ExtensionsService* extension_service)
    : extensions_service_(extension_service) {
}

AppLauncherHandler::~AppLauncherHandler() {}

DOMMessageHandler* AppLauncherHandler::Attach(DOMUI* dom_ui) {
  // TODO(arv): Add initialization code to the Apps store etc.
  return DOMMessageHandler::Attach(dom_ui);
}

void AppLauncherHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getApps",
      NewCallback(this, &AppLauncherHandler::HandleGetApps));
  dom_ui_->RegisterMessageCallback("launchApp",
      NewCallback(this, &AppLauncherHandler::HandleLaunchApp));
}

void AppLauncherHandler::Observe(NotificationType type,
                                 const NotificationSource& source,
                                 const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::EXTENSION_LOADED:
    case NotificationType::EXTENSION_UNLOADED:
      if (dom_ui_->tab_contents())
        HandleGetApps(NULL);
      break;

    default:
      NOTREACHED();
  }
}

// static
void AppLauncherHandler::CreateAppInfo(Extension* extension,
                                          DictionaryValue* value) {
  value->Clear();
  value->SetString(L"id", extension->id());
  value->SetString(L"name", extension->name());
  value->SetString(L"description", extension->description());
  value->SetString(L"launch_url", extension->GetFullLaunchURL().spec());

  FilePath relative_path =
      extension->GetIconPath(Extension::EXTENSION_ICON_LARGE).relative_path();

#if defined(OS_POSIX)
  std::string path = relative_path.value();
#elif defined(OS_WIN)
  std::string path = WideToUTF8(relative_path.value());
#endif  // OS_WIN

  GURL icon_url = extension->GetResourceURL(path);
  value->SetString(L"icon", icon_url.spec());
}

void AppLauncherHandler::HandleGetApps(const Value* value) {
  ListValue list;
  const ExtensionList* extensions = extensions_service_->extensions();
  for (ExtensionList::const_iterator it = extensions->begin();
       it != extensions->end(); ++it) {
     if (TreatAsApp(*it)) {
       DictionaryValue* app_info = new DictionaryValue();
       CreateAppInfo(*it, app_info);
       list.Append(app_info);
     }
  }

  dom_ui_->CallJavascriptFunction(L"getAppsCallback", list);

  // First time we get here we set up the observer so that we can tell update
  // the apps as they change.
  if (registrar_.IsEmpty()) {
    registrar_.Add(this, NotificationType::EXTENSION_LOADED,
        NotificationService::AllSources());
    registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
        NotificationService::AllSources());
  }
}

void AppLauncherHandler::HandleLaunchApp(const Value* value) {
  if (!value->IsType(Value::TYPE_LIST)) {
    NOTREACHED();
    return;
  }

  std::string extension_id;
  const ListValue* list = static_cast<const ListValue*>(value);
  if (list->GetSize() == 0 || !list->GetString(0, &extension_id)) {
    NOTREACHED();
    return;
  }

  // The extension should be a valid app because we keep the NTP up to date
  // with changes by observing EXTENSION_LOADED and EXTENSION_UNLOADED.
  Extension* extension = extensions_service_->GetExtensionById(
      extension_id, false);  // Don't include disabled.
  DCHECK(extension);
  DCHECK(extension->GetFullLaunchURL().is_valid());

  Browser::OpenApplicationTab(extensions_service_->profile(), extension);
}
<commit_msg>respect app launch container<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 "chrome/browser/dom_ui/app_launcher_handler.h"

#include "app/resource_bundle.h"
#include "base/base64.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "grit/browser_resources.h"

namespace {

bool TreatAsApp(const Extension* extension) {
  return !extension->GetFullLaunchURL().is_empty();
}

}  // namespace

AppLauncherHandler::AppLauncherHandler(
    ExtensionsService* extension_service)
    : extensions_service_(extension_service) {
}

AppLauncherHandler::~AppLauncherHandler() {}

DOMMessageHandler* AppLauncherHandler::Attach(DOMUI* dom_ui) {
  // TODO(arv): Add initialization code to the Apps store etc.
  return DOMMessageHandler::Attach(dom_ui);
}

void AppLauncherHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getApps",
      NewCallback(this, &AppLauncherHandler::HandleGetApps));
  dom_ui_->RegisterMessageCallback("launchApp",
      NewCallback(this, &AppLauncherHandler::HandleLaunchApp));
}

void AppLauncherHandler::Observe(NotificationType type,
                                 const NotificationSource& source,
                                 const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::EXTENSION_LOADED:
    case NotificationType::EXTENSION_UNLOADED:
      if (dom_ui_->tab_contents())
        HandleGetApps(NULL);
      break;

    default:
      NOTREACHED();
  }
}

// static
void AppLauncherHandler::CreateAppInfo(Extension* extension,
                                          DictionaryValue* value) {
  value->Clear();
  value->SetString(L"id", extension->id());
  value->SetString(L"name", extension->name());
  value->SetString(L"description", extension->description());
  value->SetString(L"launch_url", extension->GetFullLaunchURL().spec());

  FilePath relative_path =
      extension->GetIconPath(Extension::EXTENSION_ICON_LARGE).relative_path();

#if defined(OS_POSIX)
  std::string path = relative_path.value();
#elif defined(OS_WIN)
  std::string path = WideToUTF8(relative_path.value());
#endif  // OS_WIN

  GURL icon_url = extension->GetResourceURL(path);
  value->SetString(L"icon", icon_url.spec());
}

void AppLauncherHandler::HandleGetApps(const Value* value) {
  ListValue list;
  const ExtensionList* extensions = extensions_service_->extensions();
  for (ExtensionList::const_iterator it = extensions->begin();
       it != extensions->end(); ++it) {
     if (TreatAsApp(*it)) {
       DictionaryValue* app_info = new DictionaryValue();
       CreateAppInfo(*it, app_info);
       list.Append(app_info);
     }
  }

  dom_ui_->CallJavascriptFunction(L"getAppsCallback", list);

  // First time we get here we set up the observer so that we can tell update
  // the apps as they change.
  if (registrar_.IsEmpty()) {
    registrar_.Add(this, NotificationType::EXTENSION_LOADED,
        NotificationService::AllSources());
    registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
        NotificationService::AllSources());
  }
}

void AppLauncherHandler::HandleLaunchApp(const Value* value) {
  if (!value->IsType(Value::TYPE_LIST)) {
    NOTREACHED();
    return;
  }

  std::string extension_id;
  const ListValue* list = static_cast<const ListValue*>(value);
  if (list->GetSize() == 0 || !list->GetString(0, &extension_id)) {
    NOTREACHED();
    return;
  }

  Browser::OpenApplication(extensions_service_->profile(), extension_id);
}
<|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 "chrome/browser/gtk/toolbar_star_toggle_gtk.h"

#include "app/resource_bundle.h"
#include "base/gfx/rect.h"
#include "chrome/browser/gtk/bookmark_bubble_gtk.h"
#include "grit/theme_resources.h"

ToolbarStarToggleGtk::ToolbarStarToggleGtk()
    : widget_(gtk_button_new()),
      is_starred_(false),
      unstarred_(IDR_STAR, IDR_STAR_P, IDR_STAR_H, IDR_STAR_D),
      starred_(IDR_STARRED, IDR_STARRED_P, IDR_STARRED_H, 0) {
  gtk_widget_set_size_request(widget_.get(),
                             gdk_pixbuf_get_width(unstarred_.pixbufs(0)),
                             gdk_pixbuf_get_height(unstarred_.pixbufs(0)));

  gtk_widget_set_app_paintable(widget_.get(), TRUE);
  // We effectively double-buffer by virtue of having only one image...
  gtk_widget_set_double_buffered(widget_.get(), FALSE);
  g_signal_connect(G_OBJECT(widget_.get()), "expose-event",
                   G_CALLBACK(OnExpose), this);
  GTK_WIDGET_UNSET_FLAGS(widget_.get(), GTK_CAN_FOCUS);
}

ToolbarStarToggleGtk::~ToolbarStarToggleGtk() {
  widget_.Destroy();
}

void ToolbarStarToggleGtk::ShowStarBubble(const GURL& url,
                                          bool newly_bookmarked) {
  GtkWidget* widget = widget_.get();
  gint x, y;
  gdk_window_get_origin(widget->window, &x, &y);
  x += widget->allocation.x;
  y += widget->allocation.y;
  gint width = widget->allocation.width;
  gint height = widget->allocation.height;

  BookmarkBubbleGtk::Show(gfx::Rect(x, y, width, height),
                          NULL,
                          url,
                          newly_bookmarked);
}

void ToolbarStarToggleGtk::SetStarred(bool starred) {
  is_starred_ = starred;
  gtk_widget_queue_draw(widget_.get());
}

// static
gboolean ToolbarStarToggleGtk::OnExpose(GtkWidget* widget, GdkEventExpose* e,
                                        ToolbarStarToggleGtk* button) {
  if (button->is_starred_) {
    return button->starred_.OnExpose(widget, e);
  } else {
    return button->unstarred_.OnExpose(widget, e);
  }
}
<commit_msg>Temporarily disabling the implementation of the bookmark bubble. http://crbug.com/12259<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 "chrome/browser/gtk/toolbar_star_toggle_gtk.h"

#include "app/resource_bundle.h"
#include "base/gfx/rect.h"
#include "chrome/browser/gtk/bookmark_bubble_gtk.h"
#include "grit/theme_resources.h"

ToolbarStarToggleGtk::ToolbarStarToggleGtk()
    : widget_(gtk_button_new()),
      is_starred_(false),
      unstarred_(IDR_STAR, IDR_STAR_P, IDR_STAR_H, IDR_STAR_D),
      starred_(IDR_STARRED, IDR_STARRED_P, IDR_STARRED_H, 0) {
  gtk_widget_set_size_request(widget_.get(),
                             gdk_pixbuf_get_width(unstarred_.pixbufs(0)),
                             gdk_pixbuf_get_height(unstarred_.pixbufs(0)));

  gtk_widget_set_app_paintable(widget_.get(), TRUE);
  // We effectively double-buffer by virtue of having only one image...
  gtk_widget_set_double_buffered(widget_.get(), FALSE);
  g_signal_connect(G_OBJECT(widget_.get()), "expose-event",
                   G_CALLBACK(OnExpose), this);
  GTK_WIDGET_UNSET_FLAGS(widget_.get(), GTK_CAN_FOCUS);
}

ToolbarStarToggleGtk::~ToolbarStarToggleGtk() {
  widget_.Destroy();
}

void ToolbarStarToggleGtk::ShowStarBubble(const GURL& url,
                                          bool newly_bookmarked) {
// TODO(erg): Temporarily disabling the implementation of the bookmark bubble.
// http://crbug.com/12259
#if 0
  GtkWidget* widget = widget_.get();
  gint x, y;
  gdk_window_get_origin(widget->window, &x, &y);
  x += widget->allocation.x;
  y += widget->allocation.y;
  gint width = widget->allocation.width;
  gint height = widget->allocation.height;

  BookmarkBubbleGtk::Show(gfx::Rect(x, y, width, height),
                          NULL,
                          url,
                          newly_bookmarked);
#endif
}

void ToolbarStarToggleGtk::SetStarred(bool starred) {
  is_starred_ = starred;
  gtk_widget_queue_draw(widget_.get());
}

// static
gboolean ToolbarStarToggleGtk::OnExpose(GtkWidget* widget, GdkEventExpose* e,
                                        ToolbarStarToggleGtk* button) {
  if (button->is_starred_) {
    return button->starred_.OnExpose(widget, e);
  } else {
    return button->unstarred_.OnExpose(widget, e);
  }
}
<|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/printing/print_view_manager.h"

#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_preview_tab_controller.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "chrome/common/print_messages.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_entry.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/generated_resources.h"
#include "printing/metafile.h"
#include "printing/metafile_impl.h"
#include "printing/printed_document.h"
#include "ui/base/l10n/l10n_util.h"

using base::TimeDelta;

namespace {

string16 GenerateRenderSourceName(TabContents* tab_contents) {
  string16 name(tab_contents->GetTitle());
  if (name.empty())
    name = l10n_util::GetStringUTF16(IDS_DEFAULT_PRINT_DOCUMENT_TITLE);
  return name;
}

}  // namespace

namespace printing {

PrintViewManager::PrintViewManager(TabContents* tab_contents)
    : TabContentsObserver(tab_contents),
      number_pages_(0),
      printing_succeeded_(false),
      inside_inner_message_loop_(false),
      is_title_overridden_(false) {
#if defined(OS_POSIX) && !defined(OS_MACOSX)
  expecting_first_page_ = true;
#endif
}

PrintViewManager::~PrintViewManager() {
  DisconnectFromCurrentPrintJob();
}

bool PrintViewManager::PrintNow() {
  // Don't print interstitials.
  if (tab_contents()->showing_interstitial_page())
    return false;

  return Send(new PrintMsg_PrintPages(routing_id()));
}

void PrintViewManager::StopNavigation() {
  // Cancel the current job, wait for the worker to finish.
  TerminatePrintJob(true);
}

void PrintViewManager::RenderViewGone() {
  if (!print_job_.get())
    return;

  scoped_refptr<PrintedDocument> document(print_job_->document());
  if (document) {
    // If IsComplete() returns false, the document isn't completely rendered.
    // Since our renderer is gone, there's nothing to do, cancel it. Otherwise,
    // the print job may finish without problem.
    TerminatePrintJob(!document->IsComplete());
  }
}

void PrintViewManager::OverrideTitle(TabContents* tab_contents) {
  is_title_overridden_ = true;
  overridden_title_ = GenerateRenderSourceName(tab_contents);
}

string16 PrintViewManager::RenderSourceName() {
  if (is_title_overridden_)
    return overridden_title_;
  return GenerateRenderSourceName(tab_contents());
}

GURL PrintViewManager::RenderSourceUrl() {
  NavigationEntry* entry = tab_contents()->controller().GetActiveEntry();
  if (entry)
    return entry->virtual_url();
  return GURL();
}

void PrintViewManager::OnDidGetPrintedPagesCount(int cookie, int number_pages) {
  DCHECK_GT(cookie, 0);
  DCHECK_GT(number_pages, 0);
  number_pages_ = number_pages;
  if (!OpportunisticallyCreatePrintJob(cookie))
    return;

  PrintedDocument* document = print_job_->document();
  if (!document || cookie != document->cookie()) {
    // Out of sync. It may happens since we are completely asynchronous. Old
    // spurious message can happen if one of the processes is overloaded.
    return;
  }
}

void PrintViewManager::OnDidPrintPage(
    const PrintHostMsg_DidPrintPage_Params& params) {
  if (!OpportunisticallyCreatePrintJob(params.document_cookie))
    return;

  PrintedDocument* document = print_job_->document();
  if (!document || params.document_cookie != document->cookie()) {
    // Out of sync. It may happen since we are completely asynchronous. Old
    // spurious messages can be received if one of the processes is overloaded.
    return;
  }

#if defined(OS_WIN)
  // http://msdn2.microsoft.com/en-us/library/ms535522.aspx
  // Windows 2000/XP: When a page in a spooled file exceeds approximately 350
  // MB, it can fail to print and not send an error message.
  if (params.data_size && params.data_size >= 350*1024*1024) {
    NOTREACHED() << "size:" << params.data_size;
    TerminatePrintJob(true);
    tab_contents()->Stop();
    return;
  }
#endif

#if defined(OS_WIN) || defined(OS_MACOSX)
  const bool metafile_must_be_valid = true;
#elif defined(OS_POSIX)
  const bool metafile_must_be_valid = expecting_first_page_;
  expecting_first_page_ = false;
#endif

  base::SharedMemory shared_buf(params.metafile_data_handle, true);
  if (metafile_must_be_valid) {
    if (!shared_buf.Map(params.data_size)) {
      NOTREACHED() << "couldn't map";
      tab_contents()->Stop();
      return;
    }
  }

  scoped_ptr<Metafile> metafile(new NativeMetafile);
  if (metafile_must_be_valid) {
    if (!metafile->InitFromData(shared_buf.memory(), params.data_size)) {
      NOTREACHED() << "Invalid metafile header";
      tab_contents()->Stop();
      return;
    }
  }

  // Update the rendered document. It will send notifications to the listener.
  document->SetPage(params.page_number,
                    metafile.release(),
                    params.actual_shrink,
                    params.page_size,
                    params.content_area,
                    params.has_visible_overlays);

  ShouldQuitFromInnerMessageLoop();
}

bool PrintViewManager::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PrintViewManager, message)
    IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPrintedPagesCount,
                        OnDidGetPrintedPagesCount)
    IPC_MESSAGE_HANDLER(PrintHostMsg_DidPrintPage, OnDidPrintPage)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PrintViewManager::Observe(NotificationType type,
                               const NotificationSource& source,
                               const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::PRINT_JOB_EVENT: {
      OnNotifyPrintJobEvent(*Details<JobEventDetails>(details).ptr());
      break;
    }
    default: {
      NOTREACHED();
      break;
    }
  }
}

void PrintViewManager::OnNotifyPrintJobEvent(
    const JobEventDetails& event_details) {
  switch (event_details.type()) {
    case JobEventDetails::FAILED: {
      TerminatePrintJob(true);
      break;
    }
    case JobEventDetails::USER_INIT_DONE:
    case JobEventDetails::DEFAULT_INIT_DONE:
    case JobEventDetails::USER_INIT_CANCELED: {
      NOTREACHED();
      break;
    }
    case JobEventDetails::ALL_PAGES_REQUESTED: {
      ShouldQuitFromInnerMessageLoop();
      break;
    }
    case JobEventDetails::NEW_DOC:
    case JobEventDetails::NEW_PAGE:
    case JobEventDetails::PAGE_DONE:
    case JobEventDetails::DOC_DONE: {
      // Don't care about the actual printing process.
      break;
    }
    case JobEventDetails::JOB_DONE: {
      // Printing is done, we don't need it anymore.
      // print_job_->is_job_pending() may still be true, depending on the order
      // of object registration.
      printing_succeeded_ = true;
      ReleasePrintJob();
      break;
    }
    default: {
      NOTREACHED();
      break;
    }
  }
}

bool PrintViewManager::RenderAllMissingPagesNow() {
  if (!print_job_.get() || !print_job_->is_job_pending())
    return false;

  // We can't print if there is no renderer.
  if (!tab_contents() ||
      !tab_contents()->render_view_host() ||
      !tab_contents()->render_view_host()->IsRenderViewLive()) {
    return false;
  }

  // Is the document already complete?
  if (print_job_->document() && print_job_->document()->IsComplete()) {
    printing_succeeded_ = true;
    return true;
  }

  // TabContents is either dying or a second consecutive request to print
  // happened before the first had time to finish. We need to render all the
  // pages in an hurry if a print_job_ is still pending. No need to wait for it
  // to actually spool the pages, only to have the renderer generate them. Run
  // a message loop until we get our signal that the print job is satisfied.
  // PrintJob will send a ALL_PAGES_REQUESTED after having received all the
  // pages it needs. MessageLoop::current()->Quit() will be called as soon as
  // print_job_->document()->IsComplete() is true on either ALL_PAGES_REQUESTED
  // or in DidPrintPage(). The check is done in
  // ShouldQuitFromInnerMessageLoop().
  // BLOCKS until all the pages are received. (Need to enable recursive task)
  if (!RunInnerMessageLoop()) {
    // This function is always called from DisconnectFromCurrentPrintJob() so we
    // know that the job will be stopped/canceled in any case.
    return false;
  }
  return true;
}

void PrintViewManager::ShouldQuitFromInnerMessageLoop() {
  // Look at the reason.
  DCHECK(print_job_->document());
  if (print_job_->document() &&
      print_job_->document()->IsComplete() &&
      inside_inner_message_loop_) {
    // We are in a message loop created by RenderAllMissingPagesNow. Quit from
    // it.
    MessageLoop::current()->Quit();
    inside_inner_message_loop_ = false;
  }
}

bool PrintViewManager::CreateNewPrintJob(PrintJobWorkerOwner* job) {
  DCHECK(!inside_inner_message_loop_);

  // Disconnect the current print_job_.
  DisconnectFromCurrentPrintJob();

  // We can't print if there is no renderer.
  if (!tab_contents()->render_view_host() ||
      !tab_contents()->render_view_host()->IsRenderViewLive()) {
    return false;
  }

  // Ask the renderer to generate the print preview, create the print preview
  // view and switch to it, initialize the printer and show the print dialog.
  DCHECK(!print_job_.get());
  DCHECK(job);
  if (!job)
    return false;

  print_job_ = new PrintJob();
  print_job_->Initialize(job, this, number_pages_);
  registrar_.Add(this, NotificationType::PRINT_JOB_EVENT,
                 Source<PrintJob>(print_job_.get()));
  printing_succeeded_ = false;
  return true;
}

void PrintViewManager::DisconnectFromCurrentPrintJob() {
  // Make sure all the necessary rendered page are done. Don't bother with the
  // return value.
  bool result = RenderAllMissingPagesNow();

  // Verify that assertion.
  if (print_job_.get() &&
      print_job_->document() &&
      !print_job_->document()->IsComplete()) {
    DCHECK(!result);
    // That failed.
    TerminatePrintJob(true);
  } else {
    // DO NOT wait for the job to finish.
    ReleasePrintJob();
  }
#if defined(OS_POSIX) && !defined(OS_MACOSX)
  expecting_first_page_ = true;
#endif
}

void PrintViewManager::PrintingDone(bool success) {
  if (!print_job_.get() || !tab_contents())
    return;
  RenderViewHost* rvh = tab_contents()->render_view_host();
  rvh->Send(new PrintMsg_PrintingDone(rvh->routing_id(), success));
}

void PrintViewManager::TerminatePrintJob(bool cancel) {
  if (!print_job_.get())
    return;

  if (cancel) {
    // We don't need the metafile data anymore because the printing is canceled.
    print_job_->Cancel();
    inside_inner_message_loop_ = false;
  } else {
    DCHECK(!inside_inner_message_loop_);
    DCHECK(!print_job_->document() || print_job_->document()->IsComplete());

    // TabContents is either dying or navigating elsewhere. We need to render
    // all the pages in an hurry if a print job is still pending. This does the
    // trick since it runs a blocking message loop:
    print_job_->Stop();
  }
  ReleasePrintJob();
}

void PrintViewManager::ReleasePrintJob() {
  if (!print_job_.get())
    return;

  PrintingDone(printing_succeeded_);

  registrar_.Remove(this, NotificationType::PRINT_JOB_EVENT,
                    Source<PrintJob>(print_job_.get()));
  print_job_->DisconnectSource();
  // Don't close the worker thread.
  print_job_ = NULL;
}

bool PrintViewManager::RunInnerMessageLoop() {
  // This value may actually be too low:
  //
  // - If we're looping because of printer settings initializaton, the premise
  // here is that some poor users have their print server away on a VPN over
  // dialup. In this situation, the simple fact of opening the printer can be
  // dead slow. On the other side, we don't want to die infinitely for a real
  // network error. Give the printer 60 seconds to comply.
  //
  // - If we're looping because of renderer page generation, the renderer could
  // be cpu bound, the page overly complex/large or the system just
  // memory-bound.
  static const int kPrinterSettingsTimeout = 60000;
  base::OneShotTimer<MessageLoop> quit_timer;
  quit_timer.Start(TimeDelta::FromMilliseconds(kPrinterSettingsTimeout),
                   MessageLoop::current(), &MessageLoop::Quit);

  inside_inner_message_loop_ = true;

  // Need to enable recursive task.
  bool old_state = MessageLoop::current()->NestableTasksAllowed();
  MessageLoop::current()->SetNestableTasksAllowed(true);
  MessageLoop::current()->Run();
  // Restore task state.
  MessageLoop::current()->SetNestableTasksAllowed(old_state);

  bool success = true;
  if (inside_inner_message_loop_) {
    // Ok we timed out. That's sad.
    inside_inner_message_loop_ = false;
    success = false;
  }

  return success;
}

bool PrintViewManager::OpportunisticallyCreatePrintJob(int cookie) {
  if (print_job_.get())
    return true;

  if (!cookie) {
    // Out of sync. It may happens since we are completely asynchronous. Old
    // spurious message can happen if one of the processes is overloaded.
    return false;
  }

  // The job was initiated by a script. Time to get the corresponding worker
  // thread.
  scoped_refptr<PrinterQuery> queued_query;
  g_browser_process->print_job_manager()->PopPrinterQuery(cookie,
                                                          &queued_query);
  DCHECK(queued_query.get());
  if (!queued_query.get())
    return false;

  if (!CreateNewPrintJob(queued_query.get())) {
    // Don't kill anything.
    return false;
  }

  // Settings are already loaded. Go ahead. This will set
  // print_job_->is_job_pending() to true.
  print_job_->StartPrinting();
  return true;
}

}  // namespace printing
<commit_msg>Cleanup: Remove more dead printing code.<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/printing/print_view_manager.h"

#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_preview_tab_controller.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "chrome/common/print_messages.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_entry.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/generated_resources.h"
#include "printing/metafile.h"
#include "printing/metafile_impl.h"
#include "printing/printed_document.h"
#include "ui/base/l10n/l10n_util.h"

using base::TimeDelta;

namespace {

string16 GenerateRenderSourceName(TabContents* tab_contents) {
  string16 name(tab_contents->GetTitle());
  if (name.empty())
    name = l10n_util::GetStringUTF16(IDS_DEFAULT_PRINT_DOCUMENT_TITLE);
  return name;
}

}  // namespace

namespace printing {

PrintViewManager::PrintViewManager(TabContents* tab_contents)
    : TabContentsObserver(tab_contents),
      number_pages_(0),
      printing_succeeded_(false),
      inside_inner_message_loop_(false),
      is_title_overridden_(false) {
#if defined(OS_POSIX) && !defined(OS_MACOSX)
  expecting_first_page_ = true;
#endif
}

PrintViewManager::~PrintViewManager() {
  DisconnectFromCurrentPrintJob();
}

bool PrintViewManager::PrintNow() {
  // Don't print interstitials.
  if (tab_contents()->showing_interstitial_page())
    return false;

  return Send(new PrintMsg_PrintPages(routing_id()));
}

void PrintViewManager::StopNavigation() {
  // Cancel the current job, wait for the worker to finish.
  TerminatePrintJob(true);
}

void PrintViewManager::RenderViewGone() {
  if (!print_job_.get())
    return;

  scoped_refptr<PrintedDocument> document(print_job_->document());
  if (document) {
    // If IsComplete() returns false, the document isn't completely rendered.
    // Since our renderer is gone, there's nothing to do, cancel it. Otherwise,
    // the print job may finish without problem.
    TerminatePrintJob(!document->IsComplete());
  }
}

void PrintViewManager::OverrideTitle(TabContents* tab_contents) {
  is_title_overridden_ = true;
  overridden_title_ = GenerateRenderSourceName(tab_contents);
}

string16 PrintViewManager::RenderSourceName() {
  if (is_title_overridden_)
    return overridden_title_;
  return GenerateRenderSourceName(tab_contents());
}

GURL PrintViewManager::RenderSourceUrl() {
  NavigationEntry* entry = tab_contents()->controller().GetActiveEntry();
  if (entry)
    return entry->virtual_url();
  return GURL();
}

void PrintViewManager::OnDidGetPrintedPagesCount(int cookie, int number_pages) {
  DCHECK_GT(cookie, 0);
  DCHECK_GT(number_pages, 0);
  number_pages_ = number_pages;
  OpportunisticallyCreatePrintJob(cookie);
}

void PrintViewManager::OnDidPrintPage(
    const PrintHostMsg_DidPrintPage_Params& params) {
  if (!OpportunisticallyCreatePrintJob(params.document_cookie))
    return;

  PrintedDocument* document = print_job_->document();
  if (!document || params.document_cookie != document->cookie()) {
    // Out of sync. It may happen since we are completely asynchronous. Old
    // spurious messages can be received if one of the processes is overloaded.
    return;
  }

#if defined(OS_WIN)
  // http://msdn2.microsoft.com/en-us/library/ms535522.aspx
  // Windows 2000/XP: When a page in a spooled file exceeds approximately 350
  // MB, it can fail to print and not send an error message.
  if (params.data_size && params.data_size >= 350*1024*1024) {
    NOTREACHED() << "size:" << params.data_size;
    TerminatePrintJob(true);
    tab_contents()->Stop();
    return;
  }
#endif

#if defined(OS_WIN) || defined(OS_MACOSX)
  const bool metafile_must_be_valid = true;
#elif defined(OS_POSIX)
  const bool metafile_must_be_valid = expecting_first_page_;
  expecting_first_page_ = false;
#endif

  base::SharedMemory shared_buf(params.metafile_data_handle, true);
  if (metafile_must_be_valid) {
    if (!shared_buf.Map(params.data_size)) {
      NOTREACHED() << "couldn't map";
      tab_contents()->Stop();
      return;
    }
  }

  scoped_ptr<Metafile> metafile(new NativeMetafile);
  if (metafile_must_be_valid) {
    if (!metafile->InitFromData(shared_buf.memory(), params.data_size)) {
      NOTREACHED() << "Invalid metafile header";
      tab_contents()->Stop();
      return;
    }
  }

  // Update the rendered document. It will send notifications to the listener.
  document->SetPage(params.page_number,
                    metafile.release(),
                    params.actual_shrink,
                    params.page_size,
                    params.content_area,
                    params.has_visible_overlays);

  ShouldQuitFromInnerMessageLoop();
}

bool PrintViewManager::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PrintViewManager, message)
    IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPrintedPagesCount,
                        OnDidGetPrintedPagesCount)
    IPC_MESSAGE_HANDLER(PrintHostMsg_DidPrintPage, OnDidPrintPage)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PrintViewManager::Observe(NotificationType type,
                               const NotificationSource& source,
                               const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::PRINT_JOB_EVENT: {
      OnNotifyPrintJobEvent(*Details<JobEventDetails>(details).ptr());
      break;
    }
    default: {
      NOTREACHED();
      break;
    }
  }
}

void PrintViewManager::OnNotifyPrintJobEvent(
    const JobEventDetails& event_details) {
  switch (event_details.type()) {
    case JobEventDetails::FAILED: {
      TerminatePrintJob(true);
      break;
    }
    case JobEventDetails::USER_INIT_DONE:
    case JobEventDetails::DEFAULT_INIT_DONE:
    case JobEventDetails::USER_INIT_CANCELED: {
      NOTREACHED();
      break;
    }
    case JobEventDetails::ALL_PAGES_REQUESTED: {
      ShouldQuitFromInnerMessageLoop();
      break;
    }
    case JobEventDetails::NEW_DOC:
    case JobEventDetails::NEW_PAGE:
    case JobEventDetails::PAGE_DONE:
    case JobEventDetails::DOC_DONE: {
      // Don't care about the actual printing process.
      break;
    }
    case JobEventDetails::JOB_DONE: {
      // Printing is done, we don't need it anymore.
      // print_job_->is_job_pending() may still be true, depending on the order
      // of object registration.
      printing_succeeded_ = true;
      ReleasePrintJob();
      break;
    }
    default: {
      NOTREACHED();
      break;
    }
  }
}

bool PrintViewManager::RenderAllMissingPagesNow() {
  if (!print_job_.get() || !print_job_->is_job_pending())
    return false;

  // We can't print if there is no renderer.
  if (!tab_contents() ||
      !tab_contents()->render_view_host() ||
      !tab_contents()->render_view_host()->IsRenderViewLive()) {
    return false;
  }

  // Is the document already complete?
  if (print_job_->document() && print_job_->document()->IsComplete()) {
    printing_succeeded_ = true;
    return true;
  }

  // TabContents is either dying or a second consecutive request to print
  // happened before the first had time to finish. We need to render all the
  // pages in an hurry if a print_job_ is still pending. No need to wait for it
  // to actually spool the pages, only to have the renderer generate them. Run
  // a message loop until we get our signal that the print job is satisfied.
  // PrintJob will send a ALL_PAGES_REQUESTED after having received all the
  // pages it needs. MessageLoop::current()->Quit() will be called as soon as
  // print_job_->document()->IsComplete() is true on either ALL_PAGES_REQUESTED
  // or in DidPrintPage(). The check is done in
  // ShouldQuitFromInnerMessageLoop().
  // BLOCKS until all the pages are received. (Need to enable recursive task)
  if (!RunInnerMessageLoop()) {
    // This function is always called from DisconnectFromCurrentPrintJob() so we
    // know that the job will be stopped/canceled in any case.
    return false;
  }
  return true;
}

void PrintViewManager::ShouldQuitFromInnerMessageLoop() {
  // Look at the reason.
  DCHECK(print_job_->document());
  if (print_job_->document() &&
      print_job_->document()->IsComplete() &&
      inside_inner_message_loop_) {
    // We are in a message loop created by RenderAllMissingPagesNow. Quit from
    // it.
    MessageLoop::current()->Quit();
    inside_inner_message_loop_ = false;
  }
}

bool PrintViewManager::CreateNewPrintJob(PrintJobWorkerOwner* job) {
  DCHECK(!inside_inner_message_loop_);

  // Disconnect the current print_job_.
  DisconnectFromCurrentPrintJob();

  // We can't print if there is no renderer.
  if (!tab_contents()->render_view_host() ||
      !tab_contents()->render_view_host()->IsRenderViewLive()) {
    return false;
  }

  // Ask the renderer to generate the print preview, create the print preview
  // view and switch to it, initialize the printer and show the print dialog.
  DCHECK(!print_job_.get());
  DCHECK(job);
  if (!job)
    return false;

  print_job_ = new PrintJob();
  print_job_->Initialize(job, this, number_pages_);
  registrar_.Add(this, NotificationType::PRINT_JOB_EVENT,
                 Source<PrintJob>(print_job_.get()));
  printing_succeeded_ = false;
  return true;
}

void PrintViewManager::DisconnectFromCurrentPrintJob() {
  // Make sure all the necessary rendered page are done. Don't bother with the
  // return value.
  bool result = RenderAllMissingPagesNow();

  // Verify that assertion.
  if (print_job_.get() &&
      print_job_->document() &&
      !print_job_->document()->IsComplete()) {
    DCHECK(!result);
    // That failed.
    TerminatePrintJob(true);
  } else {
    // DO NOT wait for the job to finish.
    ReleasePrintJob();
  }
#if defined(OS_POSIX) && !defined(OS_MACOSX)
  expecting_first_page_ = true;
#endif
}

void PrintViewManager::PrintingDone(bool success) {
  if (!print_job_.get() || !tab_contents())
    return;
  RenderViewHost* rvh = tab_contents()->render_view_host();
  rvh->Send(new PrintMsg_PrintingDone(rvh->routing_id(), success));
}

void PrintViewManager::TerminatePrintJob(bool cancel) {
  if (!print_job_.get())
    return;

  if (cancel) {
    // We don't need the metafile data anymore because the printing is canceled.
    print_job_->Cancel();
    inside_inner_message_loop_ = false;
  } else {
    DCHECK(!inside_inner_message_loop_);
    DCHECK(!print_job_->document() || print_job_->document()->IsComplete());

    // TabContents is either dying or navigating elsewhere. We need to render
    // all the pages in an hurry if a print job is still pending. This does the
    // trick since it runs a blocking message loop:
    print_job_->Stop();
  }
  ReleasePrintJob();
}

void PrintViewManager::ReleasePrintJob() {
  if (!print_job_.get())
    return;

  PrintingDone(printing_succeeded_);

  registrar_.Remove(this, NotificationType::PRINT_JOB_EVENT,
                    Source<PrintJob>(print_job_.get()));
  print_job_->DisconnectSource();
  // Don't close the worker thread.
  print_job_ = NULL;
}

bool PrintViewManager::RunInnerMessageLoop() {
  // This value may actually be too low:
  //
  // - If we're looping because of printer settings initializaton, the premise
  // here is that some poor users have their print server away on a VPN over
  // dialup. In this situation, the simple fact of opening the printer can be
  // dead slow. On the other side, we don't want to die infinitely for a real
  // network error. Give the printer 60 seconds to comply.
  //
  // - If we're looping because of renderer page generation, the renderer could
  // be cpu bound, the page overly complex/large or the system just
  // memory-bound.
  static const int kPrinterSettingsTimeout = 60000;
  base::OneShotTimer<MessageLoop> quit_timer;
  quit_timer.Start(TimeDelta::FromMilliseconds(kPrinterSettingsTimeout),
                   MessageLoop::current(), &MessageLoop::Quit);

  inside_inner_message_loop_ = true;

  // Need to enable recursive task.
  bool old_state = MessageLoop::current()->NestableTasksAllowed();
  MessageLoop::current()->SetNestableTasksAllowed(true);
  MessageLoop::current()->Run();
  // Restore task state.
  MessageLoop::current()->SetNestableTasksAllowed(old_state);

  bool success = true;
  if (inside_inner_message_loop_) {
    // Ok we timed out. That's sad.
    inside_inner_message_loop_ = false;
    success = false;
  }

  return success;
}

bool PrintViewManager::OpportunisticallyCreatePrintJob(int cookie) {
  if (print_job_.get())
    return true;

  if (!cookie) {
    // Out of sync. It may happens since we are completely asynchronous. Old
    // spurious message can happen if one of the processes is overloaded.
    return false;
  }

  // The job was initiated by a script. Time to get the corresponding worker
  // thread.
  scoped_refptr<PrinterQuery> queued_query;
  g_browser_process->print_job_manager()->PopPrinterQuery(cookie,
                                                          &queued_query);
  DCHECK(queued_query.get());
  if (!queued_query.get())
    return false;

  if (!CreateNewPrintJob(queued_query.get())) {
    // Don't kill anything.
    return false;
  }

  // Settings are already loaded. Go ahead. This will set
  // print_job_->is_job_pending() to true.
  print_job_->StartPrinting();
  return true;
}

}  // namespace printing
<|endoftext|>


<commit_before>#include <cppassert/CppAssert.hpp>
#include <cppassert/details/DebugPrint.hpp>
#include <cppassert/details/AssertionMessage.hpp>
#include <cppassert/details/Helpers.hpp>
#include <cppassert/AssertionFailure.hpp>
#include <cppassert/details/StackTrace.hpp>
#include <cstdlib>
#include <cstdio>

namespace cppassert
{
using AssertionMessage = internal::AssertionMessage;

namespace internal
{

void onAssertionFailureDefaultHandler(const AssertionFailure &assertion)
{
    const std::string errorAsStr
        = CppAssert::getInstance()->formatAssertionMessage(assertion);

    PrintMessageToStdErr(errorAsStr.c_str());

#if defined(WIN32)
    /*
     * We used to call DebugBreak() on Windows, but amazingly, it causes
     * the MSVS 2010 debugger not to be able to recover a call stack.
     */
    *((int *) NULL) = 0;
    exit(3);
#elif defined(__APPLE__)
    /*
     * On Mac OS X, Breakpad ignores signals. Only real Mach exceptions are
     * trapped.
     */
    *((int *) NULL) = 0;  /* To continue from here in GDB: "return" then "continue". */
    ::abort();  /* In case above statement gets nixed by the optimizer. */
#else
    std::abort(); /* To continue from here in GDB: "signal 0". */
#endif

}

std::string formatBoolFailureMessage(const char* expressionText,
                                    const char* actualPredicateValue,
                                    const char* expectedPredicateValue)
{
    AssertionMessage msg;
    msg << "Assertion failure value of: " << expressionText
        << "\n  Actual: " << actualPredicateValue;
    msg << "\nExpected: " << expectedPredicateValue;
    return msg.str();
}

std::string formatStreamedMessage(const std::string &message)
{
    AssertionMessage msg;
    msg<<'\n'<<message;
    return msg.str();
}

std::string formatPredicateFailureMessage(const char* predicate,
                                    const char* value1Text,
                                    const char* value2Text,
                                    const std::string &value1,
                                    const std::string &value2)
{
    AssertionMessage msg;
    msg << "Assertion failure value of: ( " << value1Text <<' '<<predicate<<' '
        << value2Text<<" )";
    msg << "\n  "<<value1Text<<" evaluated to: "<<value1;
    msg << "\n  "<<value2Text<<" evaluated to: "<<value2;
    return msg.str();
}

std::string formatAssertionMessage(const AssertionFailure &assertion)
{
    AssertionMessage error;
    error<<assertion.getSourceFileName()<<':'<<assertion.getSourceFileLine()
            <<": "<<assertion.getFunctionName()<<": ";
    error<<assertion.getMessage()<<std::endl;
    error<<assertion.getStackTrace()<<std::endl;
    return error.str();
}

std::string formatStatementFailureMessage(const char *statement)
{
    AssertionMessage msg;
    msg<< "Assertion failure: "<<statement;
    return msg.str();
}

std::string formatFrame(std::uint32_t frameNumber
                        , const void *address
                        , const char *symbol )
{
    AssertionMessage msg;
    msg<<std::setw(4)<<frameNumber<<' '
        <<address<<' '
        <<symbol<<std::endl;
    return msg.str();
}
} //internal

CppAssert::CppAssert()
:assertionHandler_(internal::onAssertionFailureDefaultHandler)
{
    setDefaultFormatter();
}

CppAssert *CppAssert::getInstance()
{
    static CppAssert instance;
    return &instance;
}

void CppAssert::onAssertionFailure(const AssertionFailure &assertion)
{
    std::unique_lock<std::mutex> lock(assertionHandlerMutex_);
    assertionHandler_(assertion);
}

std::string CppAssert::getStackTraceExceptTop(std::uint32_t skip)
{
    auto frames = internal::StackTrace::getStackTrace();
    //skip current frame
    skip += 1;
    AssertionMessage msg;
    if(frames.size()>skip)
    {
        std::uint32_t frameNumber = skip;
        for(; frameNumber<frames.size(); ++frameNumber)
        {
            msg<<formatter_.formatFrame_(frameNumber-skip
                            , frames[frameNumber].getAddress()
                            , frames[frameNumber].getSymbol());
        }
    }
    return msg.str();
}

std::string CppAssert::formatBoolFailureMessage(const char* expressionText,
                                    const char* actualPredicateValue,
                                    const char* expectedPredicateValue)
{
    return formatter_.formatBoolFailure_(expressionText
                            , actualPredicateValue
                            , expectedPredicateValue);
}

std::string CppAssert::formatStreamedMessage(const std::string &message)
{
    return formatter_.formatStreamed_(message);
}

std::string CppAssert::formatPredicateFailureMessage(const char* predicate,
                                    const char* value1Text,
                                    const char* value2Text,
                                    const std::string &value1,
                                    const std::string &value2)
{
    return formatter_.formatPredicateFailure_(predicate
                        , value1Text
                        , value2Text
                        , value1
                        , value2);
}

std::string CppAssert::formatAssertionMessage(const AssertionFailure &assertion)
{
    return formatter_.formatAssertion_(assertion);
}

std::string CppAssert::formatStatementFailureMessage(const char *statement)
{
    return formatter_.formatStatementFailure_(statement);
}

void CppAssert::setAssertionHandler(AssertionHandlerType assertionHandler)
{
    if(assertionHandler)
    {
        assertionHandler_ = std::move(assertionHandler);
    }
}

void CppAssert::setDefaultHandler()
{
    assertionHandler_ = internal::onAssertionFailureDefaultHandler;
}

void CppAssert::setBooleanFailureFormatter(CppAssert::FormatBoolFailure
                                                    booleanFormatter)
{
    if(booleanFormatter)
    {
        formatter_.formatBoolFailure_ = booleanFormatter;
    }
}

void CppAssert::setPredicateFailureFormatter(CppAssert::FormatPredicateFailure
                                                    predicateFormatter)
{
    if(predicateFormatter)
    {
        formatter_.formatPredicateFailure_ = predicateFormatter;
    }
}

void CppAssert::setStatementFailureFormatter(CppAssert::FormatStatementFailure
                                                    statementFormatter)
{
    if(statementFormatter)
    {
        formatter_.formatStatementFailure_ = statementFormatter;
    }
}

void CppAssert::setStreamFormatter(CppAssert::FormatStreamed streamFormatter)
{
    if(streamFormatter)
    {
        formatter_.formatStreamed_ = streamFormatter;
    }
}

void CppAssert::setFrameFormatter(CppAssert::FormatFrame frameFormatter)
{
    if(frameFormatter)
    {
        formatter_.formatFrame_ = frameFormatter;
    }
}

void CppAssert::setAssertionFormatter(CppAssert::FormatAssertion
                                            assertionFormatter)
{
    if(assertionFormatter)
    {
        formatter_.formatAssertion_ = assertionFormatter;
    }
}

void CppAssert::setDefaultFormatter()
{
    formatter_.formatAssertion_ = internal::formatAssertionMessage;
    formatter_.formatBoolFailure_ = internal::formatBoolFailureMessage;
    formatter_.formatPredicateFailure_ = internal::formatPredicateFailureMessage;
    formatter_.formatStatementFailure_ = internal::formatStatementFailureMessage;
    formatter_.formatStreamed_ = internal::formatStreamedMessage;
    formatter_.formatFrame_ = internal::formatFrame;
}

} //asrt
<commit_msg>Locks should not be held during handling an assertion<commit_after>#include <cppassert/CppAssert.hpp>
#include <cppassert/details/DebugPrint.hpp>
#include <cppassert/details/AssertionMessage.hpp>
#include <cppassert/details/Helpers.hpp>
#include <cppassert/AssertionFailure.hpp>
#include <cppassert/details/StackTrace.hpp>
#include <cstdlib>
#include <cstdio>

namespace cppassert
{
using AssertionMessage = internal::AssertionMessage;

namespace internal
{

void onAssertionFailureDefaultHandler(const AssertionFailure &assertion)
{
    const std::string errorAsStr
        = CppAssert::getInstance()->formatAssertionMessage(assertion);

    PrintMessageToStdErr(errorAsStr.c_str());

#if defined(WIN32)
    /*
     * We used to call DebugBreak() on Windows, but amazingly, it causes
     * the MSVS 2010 debugger not to be able to recover a call stack.
     */
    *((int *) NULL) = 0;
    exit(3);
#elif defined(__APPLE__)
    /*
     * On Mac OS X, Breakpad ignores signals. Only real Mach exceptions are
     * trapped.
     */
    *((int *) NULL) = 0;  /* To continue from here in GDB: "return" then "continue". */
    ::abort();  /* In case above statement gets nixed by the optimizer. */
#else
    std::abort(); /* To continue from here in GDB: "signal 0". */
#endif

}

std::string formatBoolFailureMessage(const char* expressionText,
                                    const char* actualPredicateValue,
                                    const char* expectedPredicateValue)
{
    AssertionMessage msg;
    msg << "Assertion failure value of: " << expressionText
        << "\n  Actual: " << actualPredicateValue;
    msg << "\nExpected: " << expectedPredicateValue;
    return msg.str();
}

std::string formatStreamedMessage(const std::string &message)
{
    AssertionMessage msg;
    msg<<'\n'<<message;
    return msg.str();
}

std::string formatPredicateFailureMessage(const char* predicate,
                                    const char* value1Text,
                                    const char* value2Text,
                                    const std::string &value1,
                                    const std::string &value2)
{
    AssertionMessage msg;
    msg << "Assertion failure value of: ( " << value1Text <<' '<<predicate<<' '
        << value2Text<<" )";
    msg << "\n  "<<value1Text<<" evaluated to: "<<value1;
    msg << "\n  "<<value2Text<<" evaluated to: "<<value2;
    return msg.str();
}

std::string formatAssertionMessage(const AssertionFailure &assertion)
{
    AssertionMessage error;
    error<<assertion.getSourceFileName()<<':'<<assertion.getSourceFileLine()
            <<": "<<assertion.getFunctionName()<<": ";
    error<<assertion.getMessage()<<std::endl;
    error<<assertion.getStackTrace()<<std::endl;
    return error.str();
}

std::string formatStatementFailureMessage(const char *statement)
{
    AssertionMessage msg;
    msg<< "Assertion failure: "<<statement;
    return msg.str();
}

std::string formatFrame(std::uint32_t frameNumber
                        , const void *address
                        , const char *symbol )
{
    AssertionMessage msg;
    msg<<std::setw(4)<<frameNumber<<' '
        <<address<<' '
        <<symbol<<std::endl;
    return msg.str();
}
} //internal

CppAssert::CppAssert()
:assertionHandler_(internal::onAssertionFailureDefaultHandler)
{
    setDefaultFormatter();
}

CppAssert *CppAssert::getInstance()
{
    static CppAssert instance;
    return &instance;
}

void CppAssert::onAssertionFailure(const AssertionFailure &assertion)
{
    AssertionHandlerType assertionHandler;
    {
        std::unique_lock<std::mutex> lock(assertionHandlerMutex_);
        assertionHandler = assertionHandler_;
    }
    assertionHandler(assertion);
}

std::string CppAssert::getStackTraceExceptTop(std::uint32_t skip)
{
    auto frames = internal::StackTrace::getStackTrace();
    //skip current frame
    skip += 1;
    AssertionMessage msg;
    if(frames.size()>skip)
    {
        std::uint32_t frameNumber = skip;
        for(; frameNumber<frames.size(); ++frameNumber)
        {
            msg<<formatter_.formatFrame_(frameNumber-skip
                            , frames[frameNumber].getAddress()
                            , frames[frameNumber].getSymbol());
        }
    }
    return msg.str();
}

std::string CppAssert::formatBoolFailureMessage(const char* expressionText,
                                    const char* actualPredicateValue,
                                    const char* expectedPredicateValue)
{
    return formatter_.formatBoolFailure_(expressionText
                            , actualPredicateValue
                            , expectedPredicateValue);
}

std::string CppAssert::formatStreamedMessage(const std::string &message)
{
    return formatter_.formatStreamed_(message);
}

std::string CppAssert::formatPredicateFailureMessage(const char* predicate,
                                    const char* value1Text,
                                    const char* value2Text,
                                    const std::string &value1,
                                    const std::string &value2)
{
    return formatter_.formatPredicateFailure_(predicate
                        , value1Text
                        , value2Text
                        , value1
                        , value2);
}

std::string CppAssert::formatAssertionMessage(const AssertionFailure &assertion)
{
    return formatter_.formatAssertion_(assertion);
}

std::string CppAssert::formatStatementFailureMessage(const char *statement)
{
    return formatter_.formatStatementFailure_(statement);
}

void CppAssert::setAssertionHandler(AssertionHandlerType assertionHandler)
{
    if(assertionHandler)
    {
        assertionHandler_ = std::move(assertionHandler);
    }
}

void CppAssert::setDefaultHandler()
{
    assertionHandler_ = internal::onAssertionFailureDefaultHandler;
}

void CppAssert::setBooleanFailureFormatter(CppAssert::FormatBoolFailure
                                                    booleanFormatter)
{
    if(booleanFormatter)
    {
        formatter_.formatBoolFailure_ = booleanFormatter;
    }
}

void CppAssert::setPredicateFailureFormatter(CppAssert::FormatPredicateFailure
                                                    predicateFormatter)
{
    if(predicateFormatter)
    {
        formatter_.formatPredicateFailure_ = predicateFormatter;
    }
}

void CppAssert::setStatementFailureFormatter(CppAssert::FormatStatementFailure
                                                    statementFormatter)
{
    if(statementFormatter)
    {
        formatter_.formatStatementFailure_ = statementFormatter;
    }
}

void CppAssert::setStreamFormatter(CppAssert::FormatStreamed streamFormatter)
{
    if(streamFormatter)
    {
        formatter_.formatStreamed_ = streamFormatter;
    }
}

void CppAssert::setFrameFormatter(CppAssert::FormatFrame frameFormatter)
{
    if(frameFormatter)
    {
        formatter_.formatFrame_ = frameFormatter;
    }
}

void CppAssert::setAssertionFormatter(CppAssert::FormatAssertion
                                            assertionFormatter)
{
    if(assertionFormatter)
    {
        formatter_.formatAssertion_ = assertionFormatter;
    }
}

void CppAssert::setDefaultFormatter()
{
    formatter_.formatAssertion_ = internal::formatAssertionMessage;
    formatter_.formatBoolFailure_ = internal::formatBoolFailureMessage;
    formatter_.formatPredicateFailure_ = internal::formatPredicateFailureMessage;
    formatter_.formatStatementFailure_ = internal::formatStatementFailureMessage;
    formatter_.formatStreamed_ = internal::formatStreamedMessage;
    formatter_.formatFrame_ = internal::formatFrame;
}

} //asrt
<|endoftext|>