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

#include "ui/base/ime/input_method_imm32.h"

#include "base/basictypes.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/text_input_client.h"

namespace ui {

InputMethodIMM32::InputMethodIMM32(internal::InputMethodDelegate* delegate,
                                   HWND toplevel_window_handle)
    : InputMethodWin(delegate, toplevel_window_handle),
      enabled_(false), is_candidate_popup_open_(false),
      composing_window_handle_(NULL) {
  // In non-Aura environment, appropriate callbacks to OnFocus() and OnBlur()
  // are not implemented yet. To work around this limitation, here we use
  // "always focused" model.
  // TODO(ime): Fix the caller of OnFocus() and OnBlur() so that appropriate
  // focus event will be passed.
  InputMethodWin::OnFocus();
}

void InputMethodIMM32::OnFocus() {
  // Ignore OnFocus event for "always focused" model. See the comment in the
  // constructor.
  // TODO(ime): Implement OnFocus once the callers are fixed.
}

void InputMethodIMM32::OnBlur() {
  // Ignore OnBlur event for "always focused" model. See the comment in the
  // constructor.
  // TODO(ime): Implement OnFocus once the callers are fixed.
}

bool InputMethodIMM32::OnUntranslatedIMEMessage(
    const base::NativeEvent& event, InputMethod::NativeEventResult* result) {
  LRESULT original_result = 0;
  BOOL handled = FALSE;
  switch (event.message) {
    case WM_IME_SETCONTEXT:
      original_result = OnImeSetContext(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_STARTCOMPOSITION:
      original_result = OnImeStartComposition(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_COMPOSITION:
      original_result = OnImeComposition(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_ENDCOMPOSITION:
      original_result = OnImeEndComposition(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_REQUEST:
      original_result = OnImeRequest(
          event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_CHAR:
    case WM_SYSCHAR:
      original_result = OnChar(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_DEADCHAR:
    case WM_SYSDEADCHAR:
      original_result = OnDeadChar(
          event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_NOTIFY:
      original_result = OnImeNotify(
          event.message, event.wParam, event.lParam, &handled);
      break;
    default:
      NOTREACHED() << "Unknown IME message:" << event.message;
      break;
  }
  if (result)
    *result = original_result;
  return !!handled;
}

void InputMethodIMM32::OnTextInputTypeChanged(const TextInputClient* client) {
  if (IsTextInputClientFocused(client) && IsWindowFocused(client)) {
    imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
    UpdateIMEState();
  }
  InputMethodWin::OnTextInputTypeChanged(client);
}

void InputMethodIMM32::OnCaretBoundsChanged(const TextInputClient* client) {
  if (!enabled_ || !IsTextInputClientFocused(client) ||
      !IsWindowFocused(client)) {
    return;
  }

  // The current text input type should not be NONE if |client| is focused.
  DCHECK(!IsTextInputTypeNone());
  gfx::Rect screen_bounds(GetTextInputClient()->GetCaretBounds());

  HWND attached_window = GetAttachedWindowHandle(client);
  // TODO(ime): see comment in TextInputClient::GetCaretBounds(), this
  // conversion shouldn't be necessary.
  RECT r;
  GetClientRect(attached_window, &r);
  POINT window_point = { screen_bounds.x(), screen_bounds.y() };
  ScreenToClient(attached_window, &window_point);
  imm32_manager_.UpdateCaretRect(
      attached_window,
      gfx::Rect(gfx::Point(window_point.x, window_point.y),
                screen_bounds.size()));
}

void InputMethodIMM32::CancelComposition(const TextInputClient* client) {
  if (enabled_ && IsTextInputClientFocused(client))
    imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
}

bool InputMethodIMM32::IsCandidatePopupOpen() const {
  return is_candidate_popup_open_;
}

void InputMethodIMM32::OnWillChangeFocusedClient(
    TextInputClient* focused_before,
    TextInputClient* focused) {
  if (IsWindowFocused(focused_before)) {
    ConfirmCompositionText();
  }
}

void InputMethodIMM32::OnDidChangeFocusedClient(TextInputClient* focused_before,
                                                TextInputClient* focused) {
  if (IsWindowFocused(focused)) {
    // Force to update the input type since client's TextInputStateChanged()
    // function might not be called if text input types before the client loses
    // focus and after it acquires focus again are the same.
    OnTextInputTypeChanged(focused);

    UpdateIMEState();

    // Force to update caret bounds, in case the client thinks that the caret
    // bounds has not changed.
    OnCaretBoundsChanged(focused);
  }
}

LRESULT InputMethodIMM32::OnImeSetContext(HWND window_handle,
                                          UINT message,
                                          WPARAM wparam,
                                          LPARAM lparam,
                                          BOOL* handled) {
  if (!!wparam)
    imm32_manager_.CreateImeWindow(window_handle);

  OnInputMethodChanged();
  return imm32_manager_.SetImeWindowStyle(
      window_handle, message, wparam, lparam, handled);
}

LRESULT InputMethodIMM32::OnImeStartComposition(HWND window_handle,
                                                UINT message,
                                                WPARAM wparam,
                                                LPARAM lparam,
                                                BOOL* handled) {
  // We have to prevent WTL from calling ::DefWindowProc() because the function
  // calls ::ImmSetCompositionWindow() and ::ImmSetCandidateWindow() to
  // over-write the position of IME windows.
  *handled = TRUE;

  // Reset the composition status and create IME windows.
  composing_window_handle_ = window_handle;
  imm32_manager_.CreateImeWindow(window_handle);
  imm32_manager_.ResetComposition(window_handle);
  return 0;
}

LRESULT InputMethodIMM32::OnImeComposition(HWND window_handle,
                                           UINT message,
                                           WPARAM wparam,
                                           LPARAM lparam,
                                           BOOL* handled) {
  // We have to prevent WTL from calling ::DefWindowProc() because we do not
  // want for the IMM (Input Method Manager) to send WM_IME_CHAR messages.
  *handled = TRUE;

  // At first, update the position of the IME window.
  imm32_manager_.UpdateImeWindow(window_handle);

  // Retrieve the result string and its attributes of the ongoing composition
  // and send it to a renderer process.
  ui::CompositionText composition;
  if (imm32_manager_.GetResult(window_handle, lparam, &composition.text)) {
    if (!IsTextInputTypeNone())
      GetTextInputClient()->InsertText(composition.text);
    imm32_manager_.ResetComposition(window_handle);
    // Fall though and try reading the composition string.
    // Japanese IMEs send a message containing both GCS_RESULTSTR and
    // GCS_COMPSTR, which means an ongoing composition has been finished
    // by the start of another composition.
  }
  // Retrieve the composition string and its attributes of the ongoing
  // composition and send it to a renderer process.
  if (imm32_manager_.GetComposition(window_handle, lparam, &composition) &&
      !IsTextInputTypeNone())
    GetTextInputClient()->SetCompositionText(composition);

  return 0;
}

LRESULT InputMethodIMM32::OnImeEndComposition(HWND window_handle,
                                              UINT message,
                                              WPARAM wparam,
                                              LPARAM lparam,
                                              BOOL* handled) {
  // Let WTL call ::DefWindowProc() and release its resources.
  *handled = FALSE;

  composing_window_handle_ = NULL;

  if (!IsTextInputTypeNone() && GetTextInputClient()->HasCompositionText())
    GetTextInputClient()->ClearCompositionText();

  imm32_manager_.ResetComposition(window_handle);
  imm32_manager_.DestroyImeWindow(window_handle);
  return 0;
}

LRESULT InputMethodIMM32::OnImeNotify(UINT message,
                                      WPARAM wparam,
                                      LPARAM lparam,
                                      BOOL* handled) {
  *handled = FALSE;

  // Update |is_candidate_popup_open_|, whether a candidate window is open.
  switch (wparam) {
  case IMN_OPENCANDIDATE:
    is_candidate_popup_open_ = true;
    break;
  case IMN_CLOSECANDIDATE:
    is_candidate_popup_open_ = false;
    break;
  }

  return 0;
}

void InputMethodIMM32::ConfirmCompositionText() {
  if (composing_window_handle_)
    imm32_manager_.CleanupComposition(composing_window_handle_);

  if (!IsTextInputTypeNone()) {
    // Though above line should confirm the client's composition text by sending
    // a result text to us, in case the input method and the client are in
    // inconsistent states, we check the client's composition state again.
    if (GetTextInputClient()->HasCompositionText())
      GetTextInputClient()->ConfirmCompositionText();
  }
}

void InputMethodIMM32::UpdateIMEState() {
  // Use switch here in case we are going to add more text input types.
  // We disable input method in password field.
  const HWND window_handle = GetAttachedWindowHandle(GetTextInputClient());
  switch (GetTextInputType()) {
    case ui::TEXT_INPUT_TYPE_NONE:
    case ui::TEXT_INPUT_TYPE_PASSWORD:
      imm32_manager_.DisableIME(window_handle);
      enabled_ = false;
      break;
    default:
      imm32_manager_.EnableIME(window_handle);
      enabled_ = true;
      break;
  }

  imm32_manager_.SetTextInputMode(window_handle, GetTextInputMode());
}

}  // namespace ui
<commit_msg>Add InputScope support into InputMethodIMM32<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/ime/input_method_imm32.h"

#include "base/basictypes.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/ime/win/tsf_input_scope.h"

namespace ui {

InputMethodIMM32::InputMethodIMM32(internal::InputMethodDelegate* delegate,
                                   HWND toplevel_window_handle)
    : InputMethodWin(delegate, toplevel_window_handle),
      enabled_(false), is_candidate_popup_open_(false),
      composing_window_handle_(NULL) {
  // In non-Aura environment, appropriate callbacks to OnFocus() and OnBlur()
  // are not implemented yet. To work around this limitation, here we use
  // "always focused" model.
  // TODO(ime): Fix the caller of OnFocus() and OnBlur() so that appropriate
  // focus event will be passed.
  InputMethodWin::OnFocus();
}

void InputMethodIMM32::OnFocus() {
  // Ignore OnFocus event for "always focused" model. See the comment in the
  // constructor.
  // TODO(ime): Implement OnFocus once the callers are fixed.
}

void InputMethodIMM32::OnBlur() {
  // Ignore OnBlur event for "always focused" model. See the comment in the
  // constructor.
  // TODO(ime): Implement OnFocus once the callers are fixed.
}

bool InputMethodIMM32::OnUntranslatedIMEMessage(
    const base::NativeEvent& event, InputMethod::NativeEventResult* result) {
  LRESULT original_result = 0;
  BOOL handled = FALSE;
  switch (event.message) {
    case WM_IME_SETCONTEXT:
      original_result = OnImeSetContext(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_STARTCOMPOSITION:
      original_result = OnImeStartComposition(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_COMPOSITION:
      original_result = OnImeComposition(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_ENDCOMPOSITION:
      original_result = OnImeEndComposition(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_REQUEST:
      original_result = OnImeRequest(
          event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_CHAR:
    case WM_SYSCHAR:
      original_result = OnChar(
          event.hwnd, event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_DEADCHAR:
    case WM_SYSDEADCHAR:
      original_result = OnDeadChar(
          event.message, event.wParam, event.lParam, &handled);
      break;
    case WM_IME_NOTIFY:
      original_result = OnImeNotify(
          event.message, event.wParam, event.lParam, &handled);
      break;
    default:
      NOTREACHED() << "Unknown IME message:" << event.message;
      break;
  }
  if (result)
    *result = original_result;
  return !!handled;
}

void InputMethodIMM32::OnTextInputTypeChanged(const TextInputClient* client) {
  if (IsTextInputClientFocused(client) && IsWindowFocused(client)) {
    imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
    UpdateIMEState();
  }
  InputMethodWin::OnTextInputTypeChanged(client);
}

void InputMethodIMM32::OnCaretBoundsChanged(const TextInputClient* client) {
  if (!enabled_ || !IsTextInputClientFocused(client) ||
      !IsWindowFocused(client)) {
    return;
  }

  // The current text input type should not be NONE if |client| is focused.
  DCHECK(!IsTextInputTypeNone());
  gfx::Rect screen_bounds(GetTextInputClient()->GetCaretBounds());

  HWND attached_window = GetAttachedWindowHandle(client);
  // TODO(ime): see comment in TextInputClient::GetCaretBounds(), this
  // conversion shouldn't be necessary.
  RECT r;
  GetClientRect(attached_window, &r);
  POINT window_point = { screen_bounds.x(), screen_bounds.y() };
  ScreenToClient(attached_window, &window_point);
  imm32_manager_.UpdateCaretRect(
      attached_window,
      gfx::Rect(gfx::Point(window_point.x, window_point.y),
                screen_bounds.size()));
}

void InputMethodIMM32::CancelComposition(const TextInputClient* client) {
  if (enabled_ && IsTextInputClientFocused(client))
    imm32_manager_.CancelIME(GetAttachedWindowHandle(client));
}

bool InputMethodIMM32::IsCandidatePopupOpen() const {
  return is_candidate_popup_open_;
}

void InputMethodIMM32::OnWillChangeFocusedClient(
    TextInputClient* focused_before,
    TextInputClient* focused) {
  if (IsWindowFocused(focused_before)) {
    ConfirmCompositionText();
  }
}

void InputMethodIMM32::OnDidChangeFocusedClient(TextInputClient* focused_before,
                                                TextInputClient* focused) {
  if (IsWindowFocused(focused)) {
    // Force to update the input type since client's TextInputStateChanged()
    // function might not be called if text input types before the client loses
    // focus and after it acquires focus again are the same.
    OnTextInputTypeChanged(focused);

    UpdateIMEState();

    // Force to update caret bounds, in case the client thinks that the caret
    // bounds has not changed.
    OnCaretBoundsChanged(focused);
  }
}

LRESULT InputMethodIMM32::OnImeSetContext(HWND window_handle,
                                          UINT message,
                                          WPARAM wparam,
                                          LPARAM lparam,
                                          BOOL* handled) {
  if (!!wparam)
    imm32_manager_.CreateImeWindow(window_handle);

  OnInputMethodChanged();
  return imm32_manager_.SetImeWindowStyle(
      window_handle, message, wparam, lparam, handled);
}

LRESULT InputMethodIMM32::OnImeStartComposition(HWND window_handle,
                                                UINT message,
                                                WPARAM wparam,
                                                LPARAM lparam,
                                                BOOL* handled) {
  // We have to prevent WTL from calling ::DefWindowProc() because the function
  // calls ::ImmSetCompositionWindow() and ::ImmSetCandidateWindow() to
  // over-write the position of IME windows.
  *handled = TRUE;

  // Reset the composition status and create IME windows.
  composing_window_handle_ = window_handle;
  imm32_manager_.CreateImeWindow(window_handle);
  imm32_manager_.ResetComposition(window_handle);
  return 0;
}

LRESULT InputMethodIMM32::OnImeComposition(HWND window_handle,
                                           UINT message,
                                           WPARAM wparam,
                                           LPARAM lparam,
                                           BOOL* handled) {
  // We have to prevent WTL from calling ::DefWindowProc() because we do not
  // want for the IMM (Input Method Manager) to send WM_IME_CHAR messages.
  *handled = TRUE;

  // At first, update the position of the IME window.
  imm32_manager_.UpdateImeWindow(window_handle);

  // Retrieve the result string and its attributes of the ongoing composition
  // and send it to a renderer process.
  ui::CompositionText composition;
  if (imm32_manager_.GetResult(window_handle, lparam, &composition.text)) {
    if (!IsTextInputTypeNone())
      GetTextInputClient()->InsertText(composition.text);
    imm32_manager_.ResetComposition(window_handle);
    // Fall though and try reading the composition string.
    // Japanese IMEs send a message containing both GCS_RESULTSTR and
    // GCS_COMPSTR, which means an ongoing composition has been finished
    // by the start of another composition.
  }
  // Retrieve the composition string and its attributes of the ongoing
  // composition and send it to a renderer process.
  if (imm32_manager_.GetComposition(window_handle, lparam, &composition) &&
      !IsTextInputTypeNone())
    GetTextInputClient()->SetCompositionText(composition);

  return 0;
}

LRESULT InputMethodIMM32::OnImeEndComposition(HWND window_handle,
                                              UINT message,
                                              WPARAM wparam,
                                              LPARAM lparam,
                                              BOOL* handled) {
  // Let WTL call ::DefWindowProc() and release its resources.
  *handled = FALSE;

  composing_window_handle_ = NULL;

  if (!IsTextInputTypeNone() && GetTextInputClient()->HasCompositionText())
    GetTextInputClient()->ClearCompositionText();

  imm32_manager_.ResetComposition(window_handle);
  imm32_manager_.DestroyImeWindow(window_handle);
  return 0;
}

LRESULT InputMethodIMM32::OnImeNotify(UINT message,
                                      WPARAM wparam,
                                      LPARAM lparam,
                                      BOOL* handled) {
  *handled = FALSE;

  // Update |is_candidate_popup_open_|, whether a candidate window is open.
  switch (wparam) {
  case IMN_OPENCANDIDATE:
    is_candidate_popup_open_ = true;
    break;
  case IMN_CLOSECANDIDATE:
    is_candidate_popup_open_ = false;
    break;
  }

  return 0;
}

void InputMethodIMM32::ConfirmCompositionText() {
  if (composing_window_handle_)
    imm32_manager_.CleanupComposition(composing_window_handle_);

  if (!IsTextInputTypeNone()) {
    // Though above line should confirm the client's composition text by sending
    // a result text to us, in case the input method and the client are in
    // inconsistent states, we check the client's composition state again.
    if (GetTextInputClient()->HasCompositionText())
      GetTextInputClient()->ConfirmCompositionText();
  }
}

void InputMethodIMM32::UpdateIMEState() {
  // Use switch here in case we are going to add more text input types.
  // We disable input method in password field.
  const HWND window_handle = GetAttachedWindowHandle(GetTextInputClient());
  const TextInputType text_input_type = GetTextInputType();
  const TextInputMode text_input_mode = GetTextInputMode();
  switch (text_input_type) {
    case ui::TEXT_INPUT_TYPE_NONE:
    case ui::TEXT_INPUT_TYPE_PASSWORD:
      imm32_manager_.DisableIME(window_handle);
      enabled_ = false;
      break;
    default:
      imm32_manager_.EnableIME(window_handle);
      enabled_ = true;
      break;
  }

  imm32_manager_.SetTextInputMode(window_handle, text_input_mode);
  tsf_inputscope::SetInputScopeForTsfUnawareWindow(
      window_handle, text_input_type, text_input_mode);
}

}  // namespace ui
<|endoftext|>


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

  Program:   Texture Analysis
  Module:    $$
  Language:  C++
  Date:      $Date: xxx-xx-xx $
  Version:   $Revision: xxx $

  Copyright (c) University of North Carolina at Chapel Hill (UNC-CH) All Rights Reserved.

  See License.txt or http://www.slicer.org/copyright/copyright.txt for details.

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

#ifndef __itkScalarImageToIntensitySizeListSampleFilter_hxx
#define __itkScalarImageToIntensitySizeListSampleFilter_hxx

#include <itkLabelStatisticsImageFilter.h>
#include <itkBinaryThresholdImageFilter.h>
#include <itkConnectedComponentImageFilter.h>

#include "itkScalarImageToIntensitySizeListSampleFilter.h"

#include "itkImageFileWriter.h"

namespace itk
{
namespace Statistics {
/**
 * Constructor
 */
template< typename TInputImage >
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::ScalarImageToIntensitySizeListSampleFilter()
{
    m_MinIntensity = 0;
    m_MaxIntensity = 0;
    m_NumberOfIntensityBins = 1;

    m_MinSize = 1;
    m_MaxSize = numeric_limits<int>::max();
    m_BackgroundValue = 0;

    this->SetNumberOfRequiredInputs(1);
    this->SetNumberOfRequiredOutputs(1);
    this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) );
}

/**
 *
 */
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(const InputImageType *input)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput( 0,
                                    const_cast< InputImageType * >( input ) );
}

/**
 * Connect one of the operands for pixel-wise addition
 */
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(unsigned int index, const TInputImage *image)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput( index,
                                    const_cast< TInputImage * >( image ) );
}

/**
 *
 */
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GetInput(void) const
{
  return itkDynamicCastInDebugMode< const TInputImage * >( this->GetPrimaryInput() );
}

/**
 *
 */
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GetInput(unsigned int idx) const
{
  const TInputImage *in = dynamic_cast< const TInputImage * >
    ( this->ProcessObject::GetInput(idx) );

  if ( in == ITK_NULLPTR && this->ProcessObject::GetInput(idx) != ITK_NULLPTR )
    {
    itkWarningMacro (<< "Unable to convert input number " << idx << " to type " <<  typeid( InputImageType ).name () );
    }
  return in;
}

template< typename TInputImage >
typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::DataObjectPointer
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(idx)){
    return SampleType::New().GetPointer();
}

template< typename TImage >
void
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GenerateInputRequestedRegion()
{
  // call the superclass' implementation of this method. this should
  // copy the output requested region to the input requested region
  Superclass::GenerateInputRequestedRegion();
}

template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GenerateOutputInformation(){
    Superclass::GenerateOutputInformation();

    SampleType *output =
      static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );
    output->SetMeasurementVectorSize( 2 );
}

template< typename TImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TImage >::SampleType *
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GetOutput() const
{
  const SampleType *output =
    static_cast< const SampleType * >( this->ProcessObject::GetOutput(0) );

  return output;
}

template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GenerateData()
{

    typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > ThresholdImageFilterType;
    typedef typename ThresholdImageFilterType::Pointer ThresholdImageFilterPointerType;

    typedef itk::ConnectedComponentImageFilter <OutputImageType, OutputImageType > ConnectedComponentImageFilterType;
    typedef typename ConnectedComponentImageFilterType::Pointer                           ConnectedComponentImageFilterPointerType;

    typedef itk::LabelStatisticsImageFilter< OutputImageType, OutputImageType >  LabelStatisticsImageFilterType;
    typedef typename LabelStatisticsImageFilterType::Pointer                    LabelStatisticsImageFilterPointerType;

  InputImageConstPointer inputImage = this->GetInput();

  SampleType *output = static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );

  //Calculate the step size given the maximum intensity, minimum and the number of desired intensity bins.
  this->SetIntensityBinSize((this->GetMaxIntensity() - this->GetMinIntensity())/this->GetNumberOfIntensityBins());
  double binsize = this->GetIntensityBinSize();

  if(binsize <= 0){
      cerr<<"MaxIntesity: "<<this->GetMaxIntensity()<<endl;
      cerr<<"MinIntesity: "<<this->GetMinIntensity()<<endl;
      cerr<<"NumberOfIntensityBins: "<<this->GetNumberOfIntensityBins()<<endl;
      cerr<<"Binsize = (maxIntensity - minIntensity)/numberOfBins"<<endl;
      itkExceptionMacro("ERROR: Intensity bin size is 0. Please reduce the number of intensity bins.")
  }

  InputImagePixelType minintensity = this->GetMinIntensity();
  InputImagePixelType maxintensity = this->GetMinIntensity();

  for(int i = 0; i < this->GetNumberOfIntensityBins() && maxintensity < this->GetMaxIntensity(); i++){

      minintensity = maxintensity;
      maxintensity = minintensity + (i+1)*binsize;

      if(minintensity == this->GetBackgroundValue()){
          minintensity = maxintensity;
      }

      //Threshold the image using the threshold values
      ThresholdImageFilterPointerType thresholdfilter = ThresholdImageFilterType::New();

      thresholdfilter->SetInput(inputImage);
      thresholdfilter->SetLowerThreshold(minintensity);
      thresholdfilter->SetUpperThreshold(maxintensity);
      thresholdfilter->SetOutsideValue(0);
      thresholdfilter->SetInsideValue(255);
      thresholdfilter->Update();
      OutputImagePointerType imgthresh = thresholdfilter->GetOutput();

      //Calculate the connected components and label each one of them with a unique value
      ConnectedComponentImageFilterPointerType connectedcomponents = ConnectedComponentImageFilterType::New();
      connectedcomponents->SetInput(imgthresh);

      OutputImagePointerType imglabel = connectedcomponents->GetOutput();

//      typedef itk::ImageFileWriter< OutputImageType > ImageFileWriterType;
//      typename ImageFileWriterType::Pointer writer = ImageFileWriterType::New();
//      writer->SetInput(imglabel);
//      writer->SetFileName("temp.nrrd");
//      writer->Update();

      //Compute statistics for each label
      LabelStatisticsImageFilterPointerType labelstatistics = LabelStatisticsImageFilterType::New();
      labelstatistics->SetLabelInput(imglabel);
      labelstatistics->SetInput(imgthresh);
      labelstatistics->Update();

      typedef typename LabelStatisticsImageFilterType::ValidLabelValuesContainerType ValidLabelValuesType;
      typedef typename ValidLabelValuesType::const_iterator ValidLabelsIteratorType;

      typedef typename LabelStatisticsImageFilterType::LabelPixelType                LabelPixelType;

      ValidLabelValuesType validlabels = labelstatistics->GetValidLabelValues();

      //Get each label and insert it into the list sample
      for(ValidLabelsIteratorType vIt = validlabels.begin(); vIt != validlabels.end(); ++vIt){

          LabelPixelType labelValue = *vIt;
        if ( labelstatistics->HasLabel(labelValue) && labelValue != 0){

            double size = labelstatistics->GetCount( labelValue );
            if(this->GetMinSize() <= size && size <= this->GetMaxSize()){
                double bincenter = (minintensity + maxintensity)/2.0;

                MeasurementVectorType mv;
                mv[0] = bincenter;
                mv[1] = size;
                output->PushBack(mv);
            }

//            std::cout << "min: " << labelstatistics->GetMinimum( labelValue ) << std::endl;
//            std::cout << "max: " << labelstatistics->GetMaximum( labelValue ) << std::endl;
//            std::cout << "median: " << labelstatistics->GetMedian( labelValue ) << std::endl;
//            std::cout << "mean: " << labelstatistics->GetMean( labelValue ) << std::endl;
//            std::cout << "sigma: " << labelstatistics->GetSigma( labelValue ) << std::endl;
//            std::cout << "variance: " << labelstatistics->GetVariance( labelValue ) << std::endl;
//            std::cout << "sum: " << labelstatistics->GetSum( labelValue ) << std::endl;
//            std::cout << "count: " << labelstatistics->GetCount( labelValue ) << std::endl;
//            std::cout << "region: " << labelstatistics->GetRegion( labelValue ) << std::endl;
//            std::cout << std::endl << std::endl;
        }
      }

  }

}

template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
    Superclass::PrintSelf(os, indent);
    os << indent << "ScalarImageToIntensityListSampleFilter: "<< std::endl;
    os << indent << "SamplePointerType: "<< this->GetOutput() <<endl;
    os << indent << "MinIntensity: "<<m_MinIntensity <<endl;
    os << indent << "MaxIntensity: "<<m_MaxIntensity<<endl;
    os << indent << "BackgroundValue: "<< m_BackgroundValue <<endl;
    os << indent << "NumberOfIntensityBins: "<< m_NumberOfIntensityBins <<endl;

    os << indent << "MinSize: "<< m_MinSize <<endl;
    os << indent << "MaxSize: "<< m_MaxSize <<endl;
}

}// namespace statistics
}// namespace itk

#endif
<commit_msg>BUG: Increase of bin size<commit_after>/*=========================================================================

  Program:   Texture Analysis
  Module:    $$
  Language:  C++
  Date:      $Date: xxx-xx-xx $
  Version:   $Revision: xxx $

  Copyright (c) University of North Carolina at Chapel Hill (UNC-CH) All Rights Reserved.

  See License.txt or http://www.slicer.org/copyright/copyright.txt for details.

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

#ifndef __itkScalarImageToIntensitySizeListSampleFilter_hxx
#define __itkScalarImageToIntensitySizeListSampleFilter_hxx

#include <itkLabelStatisticsImageFilter.h>
#include <itkBinaryThresholdImageFilter.h>
#include <itkConnectedComponentImageFilter.h>

#include "itkScalarImageToIntensitySizeListSampleFilter.h"

#include "itkImageFileWriter.h"

namespace itk
{
namespace Statistics {
/**
 * Constructor
 */
template< typename TInputImage >
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::ScalarImageToIntensitySizeListSampleFilter()
{
    m_MinIntensity = 0;
    m_MaxIntensity = 0;
    m_NumberOfIntensityBins = 1;

    m_MinSize = 1;
    m_MaxSize = numeric_limits<int>::max();
    m_BackgroundValue = 0;

    this->SetNumberOfRequiredInputs(1);
    this->SetNumberOfRequiredOutputs(1);
    this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) );
}

/**
 *
 */
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(const InputImageType *input)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput( 0,
                                    const_cast< InputImageType * >( input ) );
}

/**
 * Connect one of the operands for pixel-wise addition
 */
template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::SetInput(unsigned int index, const TInputImage *image)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput( index,
                                    const_cast< TInputImage * >( image ) );
}

/**
 *
 */
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GetInput(void) const
{
  return itkDynamicCastInDebugMode< const TInputImage * >( this->GetPrimaryInput() );
}

/**
 *
 */
template< typename TInputImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::InputImageType *
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GetInput(unsigned int idx) const
{
  const TInputImage *in = dynamic_cast< const TInputImage * >
    ( this->ProcessObject::GetInput(idx) );

  if ( in == ITK_NULLPTR && this->ProcessObject::GetInput(idx) != ITK_NULLPTR )
    {
    itkWarningMacro (<< "Unable to convert input number " << idx << " to type " <<  typeid( InputImageType ).name () );
    }
  return in;
}

template< typename TInputImage >
typename ScalarImageToIntensitySizeListSampleFilter< TInputImage >::DataObjectPointer
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::MakeOutput(DataObjectPointerArraySizeType itkNotUsed(idx)){
    return SampleType::New().GetPointer();
}

template< typename TImage >
void
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GenerateInputRequestedRegion()
{
  // call the superclass' implementation of this method. this should
  // copy the output requested region to the input requested region
  Superclass::GenerateInputRequestedRegion();
}

template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >::GenerateOutputInformation(){
    Superclass::GenerateOutputInformation();

    SampleType *output =
      static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );
    output->SetMeasurementVectorSize( 2 );
}

template< typename TImage >
const typename ScalarImageToIntensitySizeListSampleFilter< TImage >::SampleType *
ScalarImageToIntensitySizeListSampleFilter< TImage >
::GetOutput() const
{
  const SampleType *output =
    static_cast< const SampleType * >( this->ProcessObject::GetOutput(0) );

  return output;
}

template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::GenerateData()
{

    typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > ThresholdImageFilterType;
    typedef typename ThresholdImageFilterType::Pointer ThresholdImageFilterPointerType;

    typedef itk::ConnectedComponentImageFilter <OutputImageType, OutputImageType > ConnectedComponentImageFilterType;
    typedef typename ConnectedComponentImageFilterType::Pointer                           ConnectedComponentImageFilterPointerType;

    typedef itk::LabelStatisticsImageFilter< OutputImageType, OutputImageType >  LabelStatisticsImageFilterType;
    typedef typename LabelStatisticsImageFilterType::Pointer                    LabelStatisticsImageFilterPointerType;

  InputImageConstPointer inputImage = this->GetInput();

  SampleType *output = static_cast< SampleType * >( this->ProcessObject::GetOutput(0) );

  //Calculate the step size given the maximum intensity, minimum and the number of desired intensity bins.
  this->SetIntensityBinSize((this->GetMaxIntensity() - this->GetMinIntensity())/this->GetNumberOfIntensityBins());
  double binsize = this->GetIntensityBinSize();

  if(binsize <= 0){
      cerr<<"MaxIntesity: "<<this->GetMaxIntensity()<<endl;
      cerr<<"MinIntesity: "<<this->GetMinIntensity()<<endl;
      cerr<<"NumberOfIntensityBins: "<<this->GetNumberOfIntensityBins()<<endl;
      cerr<<"Binsize = (maxIntensity - minIntensity)/numberOfBins"<<endl;
      itkExceptionMacro("ERROR: Intensity bin size is 0.")
  }

  InputImagePixelType minintensity = this->GetMinIntensity();
  InputImagePixelType maxintensity = this->GetMinIntensity();

  for(int i = 0; i < this->GetNumberOfIntensityBins() && maxintensity < this->GetMaxIntensity(); i++){

      minintensity = maxintensity;
      maxintensity = minintensity + binsize;

      //Threshold the image using the threshold values
      ThresholdImageFilterPointerType thresholdfilter = ThresholdImageFilterType::New();

      thresholdfilter->SetInput(inputImage);
      thresholdfilter->SetLowerThreshold(minintensity);
      thresholdfilter->SetUpperThreshold(maxintensity);
      thresholdfilter->SetOutsideValue(0);
      thresholdfilter->SetInsideValue(255);
      thresholdfilter->Update();
      OutputImagePointerType imgthresh = thresholdfilter->GetOutput();

      //Calculate the connected components and label each one of them with a unique value
      ConnectedComponentImageFilterPointerType connectedcomponents = ConnectedComponentImageFilterType::New();
      connectedcomponents->SetInput(imgthresh);

      OutputImagePointerType imglabel = connectedcomponents->GetOutput();

//      typedef itk::ImageFileWriter< OutputImageType > ImageFileWriterType;
//      typename ImageFileWriterType::Pointer writer = ImageFileWriterType::New();
//      writer->SetInput(imglabel);
//      writer->SetFileName("temp.nrrd");
//      writer->Update();

      //Compute statistics for each label
      LabelStatisticsImageFilterPointerType labelstatistics = LabelStatisticsImageFilterType::New();
      labelstatistics->SetLabelInput(imglabel);
      labelstatistics->SetInput(imgthresh);
      labelstatistics->Update();

      typedef typename LabelStatisticsImageFilterType::ValidLabelValuesContainerType ValidLabelValuesType;
      typedef typename ValidLabelValuesType::const_iterator ValidLabelsIteratorType;

      typedef typename LabelStatisticsImageFilterType::LabelPixelType                LabelPixelType;

      ValidLabelValuesType validlabels = labelstatistics->GetValidLabelValues();

      //Get each label and insert it into the list sample
      for(ValidLabelsIteratorType vIt = validlabels.begin(); vIt != validlabels.end(); ++vIt){

          LabelPixelType labelValue = *vIt;
        if ( labelstatistics->HasLabel(labelValue) && labelValue != 0){

            double size = labelstatistics->GetCount( labelValue );
            if(this->GetMinSize() <= size && size <= this->GetMaxSize()){
                double bincenter = (minintensity + maxintensity)/2.0;

                MeasurementVectorType mv;
                mv[0] = bincenter;
                mv[1] = size;
                output->PushBack(mv);
            }

//            std::cout << "min: " << labelstatistics->GetMinimum( labelValue ) << std::endl;
//            std::cout << "max: " << labelstatistics->GetMaximum( labelValue ) << std::endl;
//            std::cout << "median: " << labelstatistics->GetMedian( labelValue ) << std::endl;
//            std::cout << "mean: " << labelstatistics->GetMean( labelValue ) << std::endl;
//            std::cout << "sigma: " << labelstatistics->GetSigma( labelValue ) << std::endl;
//            std::cout << "variance: " << labelstatistics->GetVariance( labelValue ) << std::endl;
//            std::cout << "sum: " << labelstatistics->GetSum( labelValue ) << std::endl;
//            std::cout << "count: " << labelstatistics->GetCount( labelValue ) << std::endl;
//            std::cout << "region: " << labelstatistics->GetRegion( labelValue ) << std::endl;
//            std::cout << std::endl << std::endl;
        }
      }

  }

}

template< typename TInputImage >
void
ScalarImageToIntensitySizeListSampleFilter< TInputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
    Superclass::PrintSelf(os, indent);
    os << indent << "ScalarImageToIntensityListSampleFilter: "<< std::endl;
    os << indent << "SamplePointerType: "<< this->GetOutput() <<endl;
    os << indent << "MinIntensity: "<<m_MinIntensity <<endl;
    os << indent << "MaxIntensity: "<<m_MaxIntensity<<endl;
    os << indent << "BackgroundValue: "<< m_BackgroundValue <<endl;
    os << indent << "NumberOfIntensityBins: "<< m_NumberOfIntensityBins <<endl;

    os << indent << "MinSize: "<< m_MinSize <<endl;
    os << indent << "MaxSize: "<< m_MaxSize <<endl;
}

}// namespace statistics
}// namespace itk

#endif
<|endoftext|>


<commit_before>/*
	Al parecer, también se puede hacer gestión de lectura/escritura
	mediante otras funciones propias de C++ y sus librerias.
	El ejemplo anterior sería válido tanto para C y C++ (las funciones).
*/<commit_msg>file medium/04-ReadWrite2<commit_after>/*
	Al parecer, también se puede hacer gestión de lectura/escritura
	mediante otras funciones propias de C++ y sus librerias.
	El ejemplo anterior sería válido tanto para C y C++ (las funciones).

	ofstream: para escribir
	ifstream: para leer
	fstream: para leer/escribir
*/

#include <iostream>
#include <fstream>
#include <string>

int main() {
	//fichero para leer/escribir
	std::fstream fd;
	fd.open("readWrite2", std::ios::in | std::ios::out | std::ios::trunc);
	//Todo ok
	if (fd.is_open()) {
		//Write in file
		fd << "Linea 1\n";
		fd << "Linea 2\n";
		//Para que se escriba, por que se guarda en buffer hasta que se cierra
		fd.close();
		fd.open("readWrite2");
		//Read from file
		std::string line;
		while (std::getline(fd,line)) {
			std::cout << line << "\n";
		}
		return 0;
	} else {
		return 1;
	}
}<|endoftext|>


<commit_before>
void GetSampleName( TString inputFile="") {

  string ret;
  ret = inputFile;

  //Drell Yan
  if (inputFile.Contains("DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph"))        ret = "ZJets"   ;
  if (inputFile.Contains("DYJetsToLL_HT-200To400_TuneZ2Star_8TeV-madgraph")) ret = "ZJets200";
  if (inputFile.Contains("DYJetsToLL_HT-400ToInf_TuneZ2Star_8TeV-madgraph")) ret = "ZJets400";
  //Pythia QCD - all LO PREP
  if (inputFile.Contains("QCD_Pt-1000to1400"))  ret = "QCD1000";
  if (inputFile.Contains("QCD_Pt-120to170"))    ret = "QCD120" ;
  if (inputFile.Contains("QCD_Pt-1400to1800"))  ret = "QCD1400";
  if (inputFile.Contains("QCD_Pt-170to300"))    ret = "QCD170" ;
  if (inputFile.Contains("QCD_Pt-1800"))        ret = "QCD1800";
  if (inputFile.Contains("QCD_Pt-300to470"))    ret = "QCD300" ;
  if (inputFile.Contains("QCD30"))              ret = "QCD30"  ;
  if (inputFile.Contains("QCD_Pt-470to600"))    ret = "QCD470" ;
  if (inputFile.Contains("QCD_Pt-600to800"))    ret = "QCD600" ;
  if (inputFile.Contains("QCD_Pt-800to1000"))   ret = "QCD800" ;
  if (inputFile.Contains("QCD80"))              ret = "QCD80"  ;
  //B-jets
  if (inputFile.Contains("BJets_HT-250To500_8TeV-madgraph"))  ret = "B250" ;
  if (inputFile.Contains("BJets_HT-500To1000_8TeV-madgraph")) ret = "B500" ;
  if (inputFile.Contains("BJets_HT-1000ToInf_8TeV-madgraph")) ret = "B1000";
  //single top
  if (inputFile.Contains("_tW-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
  if (inputFile.Contains("_t-channel-DR_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_t" ;
  if (inputFile.Contains("_s-channel-DR_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_s" ;
  if (inputFile.Contains("_tW-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
  if (inputFile.Contains("_t-channel_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_t" ;
  if (inputFile.Contains("_s-channel_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_s" ;
  //W+Jets
  if (inputFile.Contains("WJetsToLNu_HT-400ToInf_8TeV-madgraph")) 			  ret = "WJets400";
  if (inputFile.Contains("WJetsToLNu_HT-250To300_8TeV-madgraph"))			  ret = "WJets250";
  if (inputFile.Contains("WJetsToLNu_HT-300To400_8TeV-madgraph")) 			  ret = "WJets300";
  if (inputFile.Contains("WJetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "WJets"   ;
  if (inputFile.Contains("W2JetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "W2Jets"  ;
  if (inputFile.Contains("W3JetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "W3Jets"  ;
  if (inputFile.Contains("W4JetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "W4Jets"  ;
  if (inputFile.Contains("WbbJetsToLNu_Massive_TuneZ2star_8TeV-madgraph-pythia6_tauola")) ret = "Wbb";
  //diboson
  if (inputFile.Contains("WZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "WZ";
  if (inputFile.Contains("WW_TuneZ2star_8TeV_pythia6_tauola")) ret = "WW";
  if (inputFile.Contains("ZZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "ZZ";
  //Z -> nu nu
  if (inputFile.Contains("ZJetsToNuNu_100_HT_200_TuneZ2Star_8TeV_madgraph")) ret = "Zinv100";
  if (inputFile.Contains("ZJetsToNuNu_200_HT_400_TuneZ2Star_8TeV_madgraph")) ret = "Zinv200";
  if (inputFile.Contains("ZJetsToNuNu_400_HT_inf_TuneZ2Star_8TeV_madgraph")) ret = "Zinv400";
  if (inputFile.Contains("ZJetsToNuNu_50_HT_100_TuneZ2Star_8TeV_madgraph"))  ret = "Zinv50" ;
  //LM
  if (inputFile.Contains("SUSY_LM9_sftsht_8TeV"))          ret = "LM9";
  //ttbar
  if (inputFile.Contains("TTJets") && inputFile.Contains("madgraph")) ret = "TTJetsMG"    ;
  if (inputFile.Contains("TTJets") && inputFile.Contains("sherpa"))   ret = "TTJetsSherpa";
  if (inputFile.Contains("TTJets") ) 				      ret = "TTJets"      ;
  if (inputFile.Contains("TT") && inputFile.Contains("mcatnlo"))      ret = "TTJets"      ;
  if (inputFile.Contains("TT") && inputFile.Contains("powheg"))       ret = "TTJets"      ;
  //
  if (inputFile.Contains("WH_WToLNu_HToBB_M-125_8TeV-powheg-herwigpp")) ret = "WH";
  if (inputFile.Contains("ZH_ZToBB_HToBB_M-125_8TeV-powheg-herwigpp"))  ret = "ZH";
  if (inputFile.Contains("TTH_HToBB_M-125_8TeV-pythia6")) ret = "TTH";
  if (inputFile.Contains("TTZJets_8TeV-madgraph_v2"))     ret = "TTZ";
  if (inputFile.Contains("TTWJets_8TeV-madgraph"))        ret = "TTW";
  //SMS
  if (inputFile.Contains("MadGraph_T1bbbb"))  ret = "T1bbbbMG";
  if (inputFile.Contains("MadGraph_T1tttt"))  ret = "T1ttttMG";
  if (inputFile.Contains("T1bbbb"))           ret = "T1bbbb"  ;
  if (inputFile.Contains("T1tttt"))           ret = "T1tttt"  ;
  if (inputFile.Contains("T2tt"))             ret = "T2tt"    ;
  if (inputFile.Contains("T2bb"))             ret = "T2bb"    ;
  if (inputFile.Contains("T5tttt"))           ret = "T5tttt"  ;
  if (inputFile.Contains("T1t1t"))            ret = "T1t1t"   ;
  if (inputFile.Contains("T1ttcc"))           ret = "T1ttcc"  ;
  if (inputFile.Contains("T7btw"))            ret = "T7btw"   ;
  if (inputFile.Contains("TChiZH"))           ret = "TChiZH"  ;
  if (inputFile.Contains("TChiHH"))           ret = "TChiHH"  ;
  if (inputFile.Contains("T6bbHH"))           ret = "T6bbHH"  ;
  if (inputFile.Contains("T6ttHH"))           ret = "T6ttHH"  ;
  if (inputFile.Contains("T5Wh"))             ret = "T5Wh"    ;
  if (inputFile.Contains("T5WH"))             ret = "T5WH"    ;
  if (inputFile.Contains("T1tbbb"))           ret = "T1tbbb"  ;
  if (inputFile.Contains("T1ttbb"))           ret = "T1ttbb"  ;
  if (inputFile.Contains("T1tttb"))           ret = "T1tttb"  ;
  if (inputFile.Contains("T2tb"))             ret = "T2tb"    ;
  //pMSSM
  if (inputFile.Contains("pMSSM")) {
    if ( inputFile.Contains("batch1") )     ret = "pMSSM_b1";
    if ( inputFile.Contains("batch2") )     ret = "pMSSM_b2";
    if ( inputFile.Contains("batch3") )     ret = "pMSSM_b3";
    if ( inputFile.Contains("batch4") )     ret = "pMSSM_b4";
  }
  if (inputFile.Contains("HbbHbb") ) ret = "hbbhbb";
  if (inputFile.Contains("TChihh") ) ret = "TChihh";
  //Otherwise not found--be careful..

  cout << ret << endl;
  return;
}
<commit_msg>add sample anmes<commit_after>
void GetSampleName( TString inputFile="") {

  string ret;
  ret = inputFile;

  //Drell Yan
  if (inputFile.Contains("DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph"))        ret = "ZJets"   ;
  if (inputFile.Contains("DYJetsToLL_HT-200To400_TuneZ2Star_8TeV-madgraph")) ret = "ZJets200";
  if (inputFile.Contains("DYJetsToLL_HT-400ToInf_TuneZ2Star_8TeV-madgraph")) ret = "ZJets400";
  //Pythia QCD - all LO PREP
  if (inputFile.Contains("QCD_Pt-1000to1400"))  ret = "QCD1000";
  if (inputFile.Contains("QCD_Pt-120to170"))    ret = "QCD120" ;
  if (inputFile.Contains("QCD_Pt-1400to1800"))  ret = "QCD1400";
  if (inputFile.Contains("QCD_Pt-170to300"))    ret = "QCD170" ;
  if (inputFile.Contains("QCD_Pt-1800"))        ret = "QCD1800";
  if (inputFile.Contains("QCD_Pt-300to470"))    ret = "QCD300" ;
  if (inputFile.Contains("QCD30"))              ret = "QCD30"  ;
  if (inputFile.Contains("QCD_Pt-470to600"))    ret = "QCD470" ;
  if (inputFile.Contains("QCD_Pt-600to800"))    ret = "QCD600" ;
  if (inputFile.Contains("QCD_Pt-800to1000"))   ret = "QCD800" ;
  if (inputFile.Contains("QCD80"))              ret = "QCD80"  ;
  //B-jets
  if (inputFile.Contains("BJets_HT-250To500_8TeV-madgraph"))  ret = "B250" ;
  if (inputFile.Contains("BJets_HT-500To1000_8TeV-madgraph")) ret = "B500" ;
  if (inputFile.Contains("BJets_HT-1000ToInf_8TeV-madgraph")) ret = "B1000";
  //single top
  if (inputFile.Contains("_tW-channel-DR_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
  if (inputFile.Contains("_t-channel-DR_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_t" ;
  if (inputFile.Contains("_s-channel-DR_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_s" ;
  if (inputFile.Contains("_tW-channel_TuneZ2star_8TeV-powheg-tauola")) ret = "t_tW";
  if (inputFile.Contains("_t-channel_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_t" ;
  if (inputFile.Contains("_s-channel_TuneZ2star_8TeV-powheg-tauola"))  ret = "t_s" ;
  //W+Jets
  if (inputFile.Contains("WJetsToLNu_HT-400ToInf_8TeV-madgraph")) 			  ret = "WJets400";
  if (inputFile.Contains("WJetsToLNu_HT-250To300_8TeV-madgraph"))			  ret = "WJets250";
  if (inputFile.Contains("WJetsToLNu_HT-300To400_8TeV-madgraph")) 			  ret = "WJets300";
  if (inputFile.Contains("WJetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "WJets"   ;
  if (inputFile.Contains("W2JetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "W2Jets"  ;
  if (inputFile.Contains("W3JetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "W3Jets"  ;
  if (inputFile.Contains("W4JetsToLNu_TuneZ2Star_8TeV-madgraph")) 			  ret = "W4Jets"  ;
  if (inputFile.Contains("WbbJetsToLNu_Massive_TuneZ2star_8TeV-madgraph-pythia6_tauola")) ret = "Wbb";
  //diboson
  if (inputFile.Contains("WZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "WZ";
  if (inputFile.Contains("WW_TuneZ2star_8TeV_pythia6_tauola")) ret = "WW";
  if (inputFile.Contains("ZZ_TuneZ2star_8TeV_pythia6_tauola")) ret = "ZZ";
  //Z -> nu nu
  if (inputFile.Contains("ZJetsToNuNu_100_HT_200_TuneZ2Star_8TeV_madgraph")) ret = "Zinv100";
  if (inputFile.Contains("ZJetsToNuNu_200_HT_400_TuneZ2Star_8TeV_madgraph")) ret = "Zinv200";
  if (inputFile.Contains("ZJetsToNuNu_400_HT_inf_TuneZ2Star_8TeV_madgraph")) ret = "Zinv400";
  if (inputFile.Contains("ZJetsToNuNu_50_HT_100_TuneZ2Star_8TeV_madgraph"))  ret = "Zinv50" ;
  //LM
  if (inputFile.Contains("SUSY_LM9_sftsht_8TeV"))          ret = "LM9";
  //ttbar
  if (inputFile.Contains("TTJets") && inputFile.Contains("madgraph")) ret = "TTJetsMG"    ;
  if (inputFile.Contains("TTJets") && inputFile.Contains("sherpa"))   ret = "TTJetsSherpa";
  if (inputFile.Contains("TTJets") ) 				      ret = "TTJets"      ;
  if (inputFile.Contains("TT") && inputFile.Contains("mcatnlo"))      ret = "TTJets"      ;
  if (inputFile.Contains("TT") && inputFile.Contains("powheg"))       ret = "TTJets"      ;
  //
  if (inputFile.Contains("WH_WToLNu_HToBB_M-125_8TeV-powheg-herwigpp")) ret = "WH";
  if (inputFile.Contains("ZH_ZToBB_HToBB_M-125_8TeV-powheg-herwigpp"))  ret = "ZH";
  if (inputFile.Contains("TTH_HToBB_M-125_8TeV-pythia6")) ret = "TTH";
  if (inputFile.Contains("TTZJets_8TeV-madgraph_v2"))     ret = "TTZ";
  if (inputFile.Contains("TTWJets_8TeV-madgraph"))        ret = "TTW";
  //SMS
  if (inputFile.Contains("MadGraph_T1bbbb"))  ret = "T1bbbbMG";
  if (inputFile.Contains("MadGraph_T1tttt"))  ret = "T1ttttMG";
  if (inputFile.Contains("T1bbbb"))           ret = "T1bbbb"  ;
  if (inputFile.Contains("T1tttt"))           ret = "T1tttt"  ;
  if (inputFile.Contains("T2tt"))             ret = "T2tt"    ;
  if (inputFile.Contains("T2bb"))             ret = "T2bb"    ;
  if (inputFile.Contains("T5tttt"))           ret = "T5tttt"  ;
  if (inputFile.Contains("T1t1t"))            ret = "T1t1t"   ;
  if (inputFile.Contains("T1ttcc"))           ret = "T1ttcc"  ;
  if (inputFile.Contains("T7btw"))            ret = "T7btw"   ;
  if (inputFile.Contains("TChiZH"))           ret = "TChiZH"  ;
  if (inputFile.Contains("TChiHH"))           ret = "TChiHH"  ;
  if (inputFile.Contains("T6bbHH"))           ret = "T6bbHH"  ;
  if (inputFile.Contains("T6ttHH"))           ret = "T6ttHH"  ;
  if (inputFile.Contains("T5Wh"))             ret = "T5Wh"    ;
  if (inputFile.Contains("T5WH"))             ret = "T5WH"    ;
  if (inputFile.Contains("T1tbbb"))           ret = "T1tbbb"  ;
  if (inputFile.Contains("T1ttbb"))           ret = "T1ttbb"  ;
  if (inputFile.Contains("T1tttb"))           ret = "T1tttb"  ;
  if (inputFile.Contains("T2tb"))             ret = "T2tb"    ;
  //pMSSM
  if (inputFile.Contains("pMSSM")) {
    if ( inputFile.Contains("batch1") )     ret = "pMSSM_b1";
    if ( inputFile.Contains("batch2") )     ret = "pMSSM_b2";
    if ( inputFile.Contains("batch3") )     ret = "pMSSM_b3";
    if ( inputFile.Contains("batch4") )     ret = "pMSSM_b4";
  }
  if (inputFile.Contains("HbbHbb") ) ret = "hbbhbb";
  if (inputFile.Contains("TChihh") ) ret = "TChihh";

  if (inputFile.Contains("MET_Run2012A"))  ret = "META";
  if (inputFile.Contains("MET_Run2012B"))  ret = "METB";
  if (inputFile.Contains("MET_Run2012C"))  ret = "METC";
  if (inputFile.Contains("MET_Run2012D"))  ret = "METD";

  //Otherwise not found--be careful..

  cout << ret << endl;
  return;
}
<|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 <math.h>
#include <stdio.h>  // FIXME(brettw) erase me.
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <time.h>

#include <algorithm>

#include "ppapi/c/dev/ppp_printing_dev.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/pp_input_event.h"
#include "ppapi/c/pp_rect.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/dev/scriptable_object_deprecated.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/var.h"

static const int kStepsPerCircle = 800;

void FlushCallback(void* data, int32_t result);

void FillRect(pp::ImageData* image, int left, int top, int width, int height,
              uint32_t color) {
  for (int y = std::max(0, top);
       y < std::min(image->size().height() - 1, top + height);
       y++) {
    for (int x = std::max(0, left);
         x < std::min(image->size().width() - 1, left + width);
         x++)
      *image->GetAddr32(pp::Point(x, y)) = color;
  }
}

class MyScriptableObject : public pp::deprecated::ScriptableObject {
 public:
  explicit MyScriptableObject(pp::Instance* instance) : instance_(instance) {}

  virtual bool HasMethod(const pp::Var& method, pp::Var* exception) {
    return method.AsString() == "toString";
  }

  virtual bool HasProperty(const pp::Var& name, pp::Var* exception) {
    if (name.is_string() && name.AsString() == "blah")
      return true;
    return false;
  }

  virtual pp::Var GetProperty(const pp::Var& name, pp::Var* exception) {
    if (name.is_string() && name.AsString() == "blah")
      return pp::Var(instance_, new MyScriptableObject(instance_));
    return pp::Var();
  }

  virtual void GetAllPropertyNames(std::vector<pp::Var>* names,
                                   pp::Var* exception) {
    names->push_back("blah");
  }

  virtual pp::Var Call(const pp::Var& method,
                       const std::vector<pp::Var>& args,
                       pp::Var* exception) {
    if (method.AsString() == "toString")
      return pp::Var("hello world");
    return pp::Var();
  }

 private:
  pp::Instance* instance_;
};

class MyFetcherClient {
 public:
  virtual void DidFetch(bool success, const std::string& data) = 0;
};

class MyFetcher {
 public:
  MyFetcher() : client_(NULL) {
    callback_factory_.Initialize(this);
  }

  void Start(const pp::Instance& instance,
             const pp::Var& url,
             MyFetcherClient* client) {
    pp::URLRequestInfo request;
    request.SetURL(url);
    request.SetMethod("GET");

    loader_ = pp::URLLoader(instance);
    client_ = client;

    pp::CompletionCallback callback =
        callback_factory_.NewCallback(&MyFetcher::DidOpen);
    int rv = loader_.Open(request, callback);
    if (rv != PP_ERROR_WOULDBLOCK)
      callback.Run(rv);
  }

  void StartWithOpenedLoader(const pp::URLLoader& loader,
                             MyFetcherClient* client) {
    loader_ = loader;
    client_ = client;

    ReadMore();
  }

 private:
  void ReadMore() {
    pp::CompletionCallback callback =
        callback_factory_.NewCallback(&MyFetcher::DidRead);
    int rv = loader_.ReadResponseBody(buf_, sizeof(buf_), callback);
    if (rv != PP_ERROR_WOULDBLOCK)
      callback.Run(rv);
  }

  void DidOpen(int32_t result) {
    if (result == PP_OK) {
      ReadMore();
    } else {
      DidFinish(result);
    }
  }

  void DidRead(int32_t result) {
    if (result > 0) {
      data_.append(buf_, result);
      ReadMore();
    } else {
      DidFinish(result);
    }
  }

  void DidFinish(int32_t result) {
    if (client_)
      client_->DidFetch(result == PP_OK, data_);
  }

  pp::CompletionCallbackFactory<MyFetcher> callback_factory_;
  pp::URLLoader loader_;
  MyFetcherClient* client_;
  char buf_[4096];
  std::string data_;
};

class MyInstance : public pp::Instance, public MyFetcherClient {
 public:
  MyInstance(PP_Instance instance)
      : pp::Instance(instance),
        time_at_last_check_(0.0),
        fetcher_(NULL),
        width_(0),
        height_(0),
        animation_counter_(0),
        print_settings_valid_(false) {}

  virtual ~MyInstance() {
    if (fetcher_) {
      delete fetcher_;
      fetcher_ = NULL;
    }
  }

  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
    return true;
  }

  virtual bool HandleDocumentLoad(const pp::URLLoader& loader) {
    fetcher_ = new MyFetcher();
    fetcher_->StartWithOpenedLoader(loader, this);
    return true;
  }

  virtual bool HandleInputEvent(const PP_InputEvent& event) {
    switch (event.type) {
      case PP_INPUTEVENT_TYPE_MOUSEDOWN:
        //SayHello();
        return true;
      case PP_INPUTEVENT_TYPE_MOUSEMOVE:
        return true;
      case PP_INPUTEVENT_TYPE_KEYDOWN:
        return true;
      default:
        return false;
    }
  }

  virtual pp::Var GetInstanceObject() {
    return pp::Var(this, new MyScriptableObject(this));
  }

  pp::ImageData PaintImage(int width, int height) {
    pp::ImageData image(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL,
                        pp::Size(width, height), false);
    if (image.is_null()) {
      printf("Couldn't allocate the image data\n");
      return image;
    }

    // Fill with semitransparent gradient.
    for (int y = 0; y < image.size().height(); y++) {
      char* row = &static_cast<char*>(image.data())[y * image.stride()];
      for (int x = 0; x < image.size().width(); x++) {
        row[x * 4 + 0] = y;
        row[x * 4 + 1] = y;
        row[x * 4 + 2] = 0;
        row[x * 4 + 3] = y;
      }
    }

    float radians = static_cast<float>(animation_counter_) / kStepsPerCircle *
        2 * 3.14159265358979F;

    float radius = static_cast<float>(std::min(width, height)) / 2.0f - 3.0f;
    int x = static_cast<int>(cos(radians) * radius + radius + 2);
    int y = static_cast<int>(sin(radians) * radius + radius + 2);

    FillRect(&image, x - 3, y - 3, 7, 7, 0x80000000);
    return image;
  }

  void Paint() {
    pp::ImageData image = PaintImage(width_, height_);
    if (!image.is_null()) {
      device_context_.ReplaceContents(&image);
      device_context_.Flush(pp::CompletionCallback(&FlushCallback, this));
    }
  }

  virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip) {
    if (position.size().width() == width_ &&
        position.size().height() == height_)
      return;  // We don't care about the position, only the size.

    width_ = position.size().width();
    height_ = position.size().height();

    device_context_ = pp::Graphics2D(this, pp::Size(width_, height_), false);
    if (!BindGraphics(device_context_)) {
      printf("Couldn't bind the device context\n");
      return;
    }

    Paint();
  }

  void UpdateFps() {
// Time code doesn't currently compile on Windows, just skip FPS for now.
#ifndef _WIN32
    pp::Var window = GetWindowObject();
    pp::Var doc = window.GetProperty("document");
    pp::Var fps = doc.Call("getElementById", "fps");

    struct timeval tv;
    struct timezone tz = {0, 0};
    gettimeofday(&tv, &tz);

    double time_now = tv.tv_sec + tv.tv_usec / 1000000.0;

    if (animation_counter_ > 0) {
      char fps_text[64];
      sprintf(fps_text, "%g fps",
              kStepsPerCircle / (time_now - time_at_last_check_));
      fps.SetProperty("innerHTML", fps_text);
    }

    time_at_last_check_ = time_now;
#endif
  }

  // Print interfaces.
  virtual PP_PrintOutputFormat_Dev* QuerySupportedPrintOutputFormats(
      uint32_t* format_count) {
    PP_PrintOutputFormat_Dev* format =
        reinterpret_cast<PP_PrintOutputFormat_Dev*>(
            pp::Module::Get()->core()->MemAlloc(
                sizeof(PP_PrintOutputFormat_Dev)));
    *format = PP_PRINTOUTPUTFORMAT_RASTER;
    *format_count = 1;
    return format;
  }

  virtual int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) {
    if (print_settings_.format != PP_PRINTOUTPUTFORMAT_RASTER)
      return 0;

    print_settings_ = print_settings;
    print_settings_valid_ = true;
    return 1;
  }

  virtual pp::Resource PrintPages(
      const PP_PrintPageNumberRange_Dev* page_ranges,
      uint32_t page_range_count) {
    if (!print_settings_valid_)
      return pp::Resource();

    if (page_range_count != 1)
      return pp::Resource();

    // Check if the page numbers are valid. We returned 1 in PrintBegin so we
    // only have 1 page to print.
    if (page_ranges[0].first_page_number || page_ranges[0].last_page_number) {
      return pp::Resource();
    }

    int width = static_cast<int>(
        (print_settings_.printable_area.size.width / 72.0) *
         print_settings_.dpi);
    int height = static_cast<int>(
        (print_settings_.printable_area.size.height / 72.0) *
         print_settings_.dpi);

    return PaintImage(width, height);
  }

  virtual void PrintEnd() {
    print_settings_valid_ = false;
  }

  void OnFlush() {
    if (animation_counter_ % kStepsPerCircle == 0)
      UpdateFps();
    animation_counter_++;
    Paint();
  }

 private:
  void Log(const pp::Var& var) {
    pp::Var doc = GetWindowObject().GetProperty("document");
    if (console_.is_undefined()) {
      pp::Var body = doc.GetProperty("body");
      console_ = doc.Call("createElement", "pre");
      console_.GetProperty("style").SetProperty("backgroundColor", "lightgray");
      body.Call("appendChild", console_);
    }
    console_.Call("appendChild", doc.Call("createTextNode", var));
    console_.Call("appendChild", doc.Call("createTextNode", "\n"));
  }

  void SayHello() {
    pp::Var window = GetWindowObject();
    pp::Var doc = window.GetProperty("document");
    pp::Var body = doc.GetProperty("body");

    pp::Var obj(this, new MyScriptableObject(this));

    // Our object should have its toString method called.
    Log("Testing MyScriptableObject::toString():");
    Log(obj);

    // body.appendChild(body) should throw an exception
    Log("\nCalling body.appendChild(body):");
    pp::Var exception;
    body.Call("appendChild", body, &exception);
    Log(exception);

    Log("\nEnumeration of window properties:");
    std::vector<pp::Var> props;
    window.GetAllPropertyNames(&props);
    for (size_t i = 0; i < props.size(); ++i)
      Log(props[i]);

    pp::Var location = window.GetProperty("location");
    pp::Var href = location.GetProperty("href");

    if (!fetcher_) {
      fetcher_ = new MyFetcher();
      fetcher_->Start(*this, href, this);
    }
  }

  void DidFetch(bool success, const std::string& data) {
    Log("\nDownloaded location.href:");
    if (success) {
      Log(data);
    } else {
      Log("Failed to download.");
    }
    delete fetcher_;
    fetcher_ = NULL;
  }

  pp::Var console_;
  pp::Graphics2D device_context_;

  double time_at_last_check_;

  MyFetcher* fetcher_;

  int width_;
  int height_;

  // Incremented for each flush we get.
  int animation_counter_;
  bool print_settings_valid_;
  PP_PrintSettings_Dev print_settings_;
};

void FlushCallback(void* data, int32_t result) {
  static_cast<MyInstance*>(data)->OnFlush();
}

class MyModule : public pp::Module {
 public:
  MyModule() : pp::Module() {}
  virtual ~MyModule() {}

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new MyInstance(instance);
  }
};

namespace pp {

// Factory function for your specialization of the Module object.
Module* CreateModule() {
  return new MyModule();
}

}  // namespace pp
<commit_msg>Added plugin size to error logging and a logging statement when the plugin size changes. I found these changes useful while debugging issues when modifying the plugin.<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 <math.h>
#include <stdio.h>  // FIXME(brettw) erase me.
#ifndef _WIN32
#include <sys/time.h>
#endif
#include <time.h>

#include <algorithm>

#include "ppapi/c/dev/ppp_printing_dev.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/pp_input_event.h"
#include "ppapi/c/pp_rect.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/dev/scriptable_object_deprecated.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/url_loader.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/var.h"

static const int kStepsPerCircle = 800;

void FlushCallback(void* data, int32_t result);

void FillRect(pp::ImageData* image, int left, int top, int width, int height,
              uint32_t color) {
  for (int y = std::max(0, top);
       y < std::min(image->size().height() - 1, top + height);
       y++) {
    for (int x = std::max(0, left);
         x < std::min(image->size().width() - 1, left + width);
         x++)
      *image->GetAddr32(pp::Point(x, y)) = color;
  }
}

class MyScriptableObject : public pp::deprecated::ScriptableObject {
 public:
  explicit MyScriptableObject(pp::Instance* instance) : instance_(instance) {}

  virtual bool HasMethod(const pp::Var& method, pp::Var* exception) {
    return method.AsString() == "toString";
  }

  virtual bool HasProperty(const pp::Var& name, pp::Var* exception) {
    if (name.is_string() && name.AsString() == "blah")
      return true;
    return false;
  }

  virtual pp::Var GetProperty(const pp::Var& name, pp::Var* exception) {
    if (name.is_string() && name.AsString() == "blah")
      return pp::Var(instance_, new MyScriptableObject(instance_));
    return pp::Var();
  }

  virtual void GetAllPropertyNames(std::vector<pp::Var>* names,
                                   pp::Var* exception) {
    names->push_back("blah");
  }

  virtual pp::Var Call(const pp::Var& method,
                       const std::vector<pp::Var>& args,
                       pp::Var* exception) {
    if (method.AsString() == "toString")
      return pp::Var("hello world");
    return pp::Var();
  }

 private:
  pp::Instance* instance_;
};

class MyFetcherClient {
 public:
  virtual void DidFetch(bool success, const std::string& data) = 0;
};

class MyFetcher {
 public:
  MyFetcher() : client_(NULL) {
    callback_factory_.Initialize(this);
  }

  void Start(const pp::Instance& instance,
             const pp::Var& url,
             MyFetcherClient* client) {
    pp::URLRequestInfo request;
    request.SetURL(url);
    request.SetMethod("GET");

    loader_ = pp::URLLoader(instance);
    client_ = client;

    pp::CompletionCallback callback =
        callback_factory_.NewCallback(&MyFetcher::DidOpen);
    int rv = loader_.Open(request, callback);
    if (rv != PP_ERROR_WOULDBLOCK)
      callback.Run(rv);
  }

  void StartWithOpenedLoader(const pp::URLLoader& loader,
                             MyFetcherClient* client) {
    loader_ = loader;
    client_ = client;

    ReadMore();
  }

 private:
  void ReadMore() {
    pp::CompletionCallback callback =
        callback_factory_.NewCallback(&MyFetcher::DidRead);
    int rv = loader_.ReadResponseBody(buf_, sizeof(buf_), callback);
    if (rv != PP_ERROR_WOULDBLOCK)
      callback.Run(rv);
  }

  void DidOpen(int32_t result) {
    if (result == PP_OK) {
      ReadMore();
    } else {
      DidFinish(result);
    }
  }

  void DidRead(int32_t result) {
    if (result > 0) {
      data_.append(buf_, result);
      ReadMore();
    } else {
      DidFinish(result);
    }
  }

  void DidFinish(int32_t result) {
    if (client_)
      client_->DidFetch(result == PP_OK, data_);
  }

  pp::CompletionCallbackFactory<MyFetcher> callback_factory_;
  pp::URLLoader loader_;
  MyFetcherClient* client_;
  char buf_[4096];
  std::string data_;
};

class MyInstance : public pp::Instance, public MyFetcherClient {
 public:
  MyInstance(PP_Instance instance)
      : pp::Instance(instance),
        time_at_last_check_(0.0),
        fetcher_(NULL),
        width_(0),
        height_(0),
        animation_counter_(0),
        print_settings_valid_(false) {}

  virtual ~MyInstance() {
    if (fetcher_) {
      delete fetcher_;
      fetcher_ = NULL;
    }
  }

  virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) {
    return true;
  }

  virtual bool HandleDocumentLoad(const pp::URLLoader& loader) {
    fetcher_ = new MyFetcher();
    fetcher_->StartWithOpenedLoader(loader, this);
    return true;
  }

  virtual bool HandleInputEvent(const PP_InputEvent& event) {
    switch (event.type) {
      case PP_INPUTEVENT_TYPE_MOUSEDOWN:
        //SayHello();
        return true;
      case PP_INPUTEVENT_TYPE_MOUSEMOVE:
        return true;
      case PP_INPUTEVENT_TYPE_KEYDOWN:
        return true;
      default:
        return false;
    }
  }

  virtual pp::Var GetInstanceObject() {
    return pp::Var(this, new MyScriptableObject(this));
  }

  pp::ImageData PaintImage(int width, int height) {
    pp::ImageData image(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL,
                        pp::Size(width, height), false);
    if (image.is_null()) {
      printf("Couldn't allocate the image data: %d, %d\n", width, height);
      return image;
    }

    // Fill with semitransparent gradient.
    for (int y = 0; y < image.size().height(); y++) {
      char* row = &static_cast<char*>(image.data())[y * image.stride()];
      for (int x = 0; x < image.size().width(); x++) {
        row[x * 4 + 0] = y;
        row[x * 4 + 1] = y;
        row[x * 4 + 2] = 0;
        row[x * 4 + 3] = y;
      }
    }

    // Draw the orbiting box.
    float radians = static_cast<float>(animation_counter_) / kStepsPerCircle *
        2 * 3.14159265358979F;

    float radius = static_cast<float>(std::min(width, height)) / 2.0f - 3.0f;
    int x = static_cast<int>(cos(radians) * radius + radius + 2);
    int y = static_cast<int>(sin(radians) * radius + radius + 2);

    const uint32_t box_bgra = 0x80000000;  // Alpha 50%.
    FillRect(&image, x - 3, y - 3, 7, 7, box_bgra);
    return image;
  }

  void Paint() {
    pp::ImageData image = PaintImage(width_, height_);
    if (!image.is_null()) {
      device_context_.ReplaceContents(&image);
      device_context_.Flush(pp::CompletionCallback(&FlushCallback, this));
    } else {
      printf("NullImage: %d, %d\n", width_, height_);
    }
  }

  virtual void DidChangeView(const pp::Rect& position, const pp::Rect& clip) {
    if (position.size().width() == width_ &&
        position.size().height() == height_)
      return;  // We don't care about the position, only the size.

    width_ = position.size().width();
    height_ = position.size().height();
    printf("DidChangeView relevant change: width=%d height:%d\n",
           width_, height_);

    device_context_ = pp::Graphics2D(this, pp::Size(width_, height_), false);
    if (!BindGraphics(device_context_)) {
      printf("Couldn't bind the device context\n");
      return;
    }

    Paint();
  }

  void UpdateFps() {
// Time code doesn't currently compile on Windows, just skip FPS for now.
#ifndef _WIN32
    pp::Var window = GetWindowObject();
    pp::Var doc = window.GetProperty("document");
    pp::Var fps = doc.Call("getElementById", "fps");

    struct timeval tv;
    struct timezone tz = {0, 0};
    gettimeofday(&tv, &tz);

    double time_now = tv.tv_sec + tv.tv_usec / 1000000.0;

    if (animation_counter_ > 0) {
      char fps_text[64];
      sprintf(fps_text, "%g fps",
              kStepsPerCircle / (time_now - time_at_last_check_));
      fps.SetProperty("innerHTML", fps_text);
    }

    time_at_last_check_ = time_now;
#endif
  }

  // Print interfaces.
  virtual PP_PrintOutputFormat_Dev* QuerySupportedPrintOutputFormats(
      uint32_t* format_count) {
    PP_PrintOutputFormat_Dev* format =
        reinterpret_cast<PP_PrintOutputFormat_Dev*>(
            pp::Module::Get()->core()->MemAlloc(
                sizeof(PP_PrintOutputFormat_Dev)));
    *format = PP_PRINTOUTPUTFORMAT_RASTER;
    *format_count = 1;
    return format;
  }

  virtual int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) {
    if (print_settings_.format != PP_PRINTOUTPUTFORMAT_RASTER)
      return 0;

    print_settings_ = print_settings;
    print_settings_valid_ = true;
    return 1;
  }

  virtual pp::Resource PrintPages(
      const PP_PrintPageNumberRange_Dev* page_ranges,
      uint32_t page_range_count) {
    if (!print_settings_valid_)
      return pp::Resource();

    if (page_range_count != 1)
      return pp::Resource();

    // Check if the page numbers are valid. We returned 1 in PrintBegin so we
    // only have 1 page to print.
    if (page_ranges[0].first_page_number || page_ranges[0].last_page_number) {
      return pp::Resource();
    }

    int width = static_cast<int>(
        (print_settings_.printable_area.size.width / 72.0) *
         print_settings_.dpi);
    int height = static_cast<int>(
        (print_settings_.printable_area.size.height / 72.0) *
         print_settings_.dpi);

    return PaintImage(width, height);
  }

  virtual void PrintEnd() {
    print_settings_valid_ = false;
  }

  void OnFlush() {
    if (animation_counter_ % kStepsPerCircle == 0)
      UpdateFps();
    animation_counter_++;
    Paint();
  }

 private:
  void Log(const pp::Var& var) {
    pp::Var doc = GetWindowObject().GetProperty("document");
    if (console_.is_undefined()) {
      pp::Var body = doc.GetProperty("body");
      console_ = doc.Call("createElement", "pre");
      console_.GetProperty("style").SetProperty("backgroundColor", "lightgray");
      body.Call("appendChild", console_);
    }
    console_.Call("appendChild", doc.Call("createTextNode", var));
    console_.Call("appendChild", doc.Call("createTextNode", "\n"));
  }

  void SayHello() {
    pp::Var window = GetWindowObject();
    pp::Var doc = window.GetProperty("document");
    pp::Var body = doc.GetProperty("body");

    pp::Var obj(this, new MyScriptableObject(this));

    // Our object should have its toString method called.
    Log("Testing MyScriptableObject::toString():");
    Log(obj);

    // body.appendChild(body) should throw an exception
    Log("\nCalling body.appendChild(body):");
    pp::Var exception;
    body.Call("appendChild", body, &exception);
    Log(exception);

    Log("\nEnumeration of window properties:");
    std::vector<pp::Var> props;
    window.GetAllPropertyNames(&props);
    for (size_t i = 0; i < props.size(); ++i)
      Log(props[i]);

    pp::Var location = window.GetProperty("location");
    pp::Var href = location.GetProperty("href");

    if (!fetcher_) {
      fetcher_ = new MyFetcher();
      fetcher_->Start(*this, href, this);
    }
  }

  void DidFetch(bool success, const std::string& data) {
    Log("\nDownloaded location.href:");
    if (success) {
      Log(data);
    } else {
      Log("Failed to download.");
    }
    delete fetcher_;
    fetcher_ = NULL;
  }

  pp::Var console_;
  pp::Graphics2D device_context_;

  double time_at_last_check_;

  MyFetcher* fetcher_;

  int width_;
  int height_;

  // Incremented for each flush we get.
  int animation_counter_;
  bool print_settings_valid_;
  PP_PrintSettings_Dev print_settings_;
};

void FlushCallback(void* data, int32_t result) {
  static_cast<MyInstance*>(data)->OnFlush();
}

class MyModule : public pp::Module {
 public:
  MyModule() : pp::Module() {}
  virtual ~MyModule() {}

  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new MyInstance(instance);
  }
};

namespace pp {

// Factory function for your specialization of the Module object.
Module* CreateModule() {
  return new MyModule();
}

}  // namespace pp
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "CustomWeapon.h"

/* system headers */
#include <sstream>
#include <string>
#include <math.h>

/* local implementation headers */
#include "WorldWeapons.h"
#include "TextUtils.h"

TimeKeeper CustomWeapon::sync = TimeKeeper::getCurrent();

const float CustomWeapon::minWeaponDelay = 0.1f;

CustomWeapon::CustomWeapon()
{
  pos[0] = pos[1] = pos[2] = 0.0f;
  rotation = 0.0f;
  size[0] = size[1] = size[2] = 1.0f;
  tilt = 0.0f;
  initdelay = 10.0f;
  delay.push_back(10.0f);
  type = Flags::Null;

  triggerType = eNullEvent;
  eventTeam = -1;
}

bool CustomWeapon::read(const char *cmd, std::istream& input) {
  if (strcmp(cmd, "initdelay") == 0) {
    input >> initdelay;
  }
  else if (strcmp(cmd, "delay") == 0) {
    std::string args;
    float d;

    delay.clear();
    std::getline(input, args);
    std::istringstream  parms(args);

    while (parms >> d) {
      if (d < minWeaponDelay) {
	std::cout << "skipping weapon delay of " << d << " seconds" << std::endl;
	continue;
      }
      else {
	delay.push_back(d);
      }
    }
    input.putback('\n');
    if (delay.size() == 0)
      return false;
  }
  else if (strcmp(cmd, "type") == 0) {
    std::string abbv;
    input >> abbv;
    type = Flag::getDescFromAbbreviation(abbv.c_str());
    if (type == NULL)
      return false;
  }
  else if (strcmp(cmd, "tilt") == 0) {
    if (!(input >> tilt)) {
      std::cout << "weapon tilt requires a value" << std::endl;
    }
    // convert to radians
    tilt = (float)(tilt * (M_PI / 180.0));
  }
  else if (strcmp(cmd, "trigger") == 0)
  {
	  std::string triggerType;
	  input >> triggerType;

	  triggerType = eNullEvent;

	  TextUtils::tolower(triggerType);
	  if ( triggerType == "oncap")
		  triggerType = eCaptureEvent;
	  else if ( triggerType == "onspawn")
		  triggerType = ePlayerSpawnEvent;
	  else if ( triggerType == "ondie")
		  triggerType = ePlayerDieEvent;
	  else
	  {
		  std::cout << "weapon trigger type:" << triggerType << " unknown" << std::endl;
	  }
  }
  else if (strcmp(cmd, "eventteam") == 0)
  {
	  input >> eventTeam;
  }
  else if (!WorldFileLocation::read(cmd, input)) {
    return false;
  }

  return true;
}

void CustomWeapon::writeToWorld(WorldInfo* world) const
{
	if (triggerType == eNullEvent)
		world->addWeapon(type, pos, rotation, tilt, initdelay, delay, sync);
	else
		worldEventManager.addEvent(triggerType,eventTeam,new WorldWeaponGlobalEventHandaler(type, pos, rotation, tilt));
}

// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>names names names<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "CustomWeapon.h"

/* system headers */
#include <sstream>
#include <string>
#include <math.h>

/* local implementation headers */
#include "WorldWeapons.h"
#include "TextUtils.h"

TimeKeeper CustomWeapon::sync = TimeKeeper::getCurrent();

const float CustomWeapon::minWeaponDelay = 0.1f;

CustomWeapon::CustomWeapon()
{
  pos[0] = pos[1] = pos[2] = 0.0f;
  rotation = 0.0f;
  size[0] = size[1] = size[2] = 1.0f;
  tilt = 0.0f;
  initdelay = 10.0f;
  delay.push_back(10.0f);
  type = Flags::Null;

  triggerType = eNullEvent;
  eventTeam = -1;
}

bool CustomWeapon::read(const char *cmd, std::istream& input) {
  if (strcmp(cmd, "initdelay") == 0) {
    input >> initdelay;
  }
  else if (strcmp(cmd, "delay") == 0) {
    std::string args;
    float d;

    delay.clear();
    std::getline(input, args);
    std::istringstream  parms(args);

    while (parms >> d) {
      if (d < minWeaponDelay) {
	std::cout << "skipping weapon delay of " << d << " seconds" << std::endl;
	continue;
      }
      else {
	delay.push_back(d);
      }
    }
    input.putback('\n');
    if (delay.size() == 0)
      return false;
  }
  else if (strcmp(cmd, "type") == 0) {
    std::string abbv;
    input >> abbv;
    type = Flag::getDescFromAbbreviation(abbv.c_str());
    if (type == NULL)
      return false;
  }
  else if (strcmp(cmd, "tilt") == 0) {
    if (!(input >> tilt)) {
      std::cout << "weapon tilt requires a value" << std::endl;
    }
    // convert to radians
    tilt = (float)(tilt * (M_PI / 180.0));
  }
  else if (strcmp(cmd, "trigger") == 0)
  {
	  std::string triggerName;
	  input >> triggerName;

	  triggerType = eNullEvent;

	  TextUtils::tolower(triggerName);
	  if ( triggerName == "oncap")
		  triggerType = eCaptureEvent;
	  else if ( triggerName == "onspawn")
		  triggerType = ePlayerSpawnEvent;
	  else if ( triggerName == "ondie")
		  triggerType = ePlayerDieEvent;
	  else
	  {
		  std::cout << "weapon trigger type:" << triggerName << " unknown" << std::endl;
	  }
  }
  else if (strcmp(cmd, "eventteam") == 0)
  {
	  input >> eventTeam;
  }
  else if (!WorldFileLocation::read(cmd, input)) {
    return false;
  }

  return true;
}

void CustomWeapon::writeToWorld(WorldInfo* world) const
{
	if (triggerType == eNullEvent)
		world->addWeapon(type, pos, rotation, tilt, initdelay, delay, sync);
	else
		worldEventManager.addEvent(triggerType,eventTeam,new WorldWeaponGlobalEventHandaler(type, pos, rotation, tilt));
}

// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>
#include "NNSound.h"
#include "NNApplication.h"
wchar_t* GetFileExtenstion (const wchar_t * file_name)
{
	wchar_t* _file_name;
	wcscpy_s(_file_name, wcslen(file_name), file_name);
	int file_name_len = wcslen (_file_name);
	_file_name +=file_name_len ;

	wchar_t *file_ext ;
	for(int i =0 ; i <file_name_len ; i ++)
	{
		if(* _file_name == '.' )
		{
			file_ext = _file_name +1 ;
			break;
		}
		_file_name --;
	}
	return file_ext ;
}

NNSound::NNSound()
	: m_Playing(false)
{
}
NNSound::~NNSound()
{
	Destroy();
}

void NNSound::Create( std::wstring path )
{
	MCI_OPEN_PARMS mciOpen = {0};
	MCIERROR mciError = {0};

	if(wcscmp(GetFileExtenstion(path.c_str()), L"mp3") == 0 )
	{
		//mp3
		mciOpen.lpstrDeviceType = L"MPEGVideo";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	else if(wcscmp(GetFileExtenstion(path.c_str()), L"wav") == 0 )
	{
		mciOpen.lpstrDeviceType = L"waveaudio";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	mciOpen.lpstrElementName = path.c_str();

	mciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );
	if ( mciError )
	{
		return;
	}

	m_MciDevice = mciOpen.wDeviceID;
	m_Playing = false;
}

void NNSound::Destroy()
{
	if ( m_Playing )
	{
		Stop();
	}
	if ( m_MciDevice )
	{
		mciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );
	}
}

void NNSound::Play()
{
	if ( !m_MciDevice )
	{
		return;
	}
	MCI_PLAY_PARMS mciPlay = {0};
	MCIERROR mciError = {0};

	mciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();
	mciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );
	if ( !mciError )
	{
		m_Playing = true;
	}
}
void NNSound::Pause()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );
}
void NNSound::Resume()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );
}
void NNSound::Stop()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );
	m_Playing = false;
}

<commit_msg>mp3, wav 재생 함수 에러 수정<commit_after>
#include "NNSound.h"
#include "NNApplication.h"
wchar_t* GetFileExtenstion (const wchar_t * file_name)
{
	wchar_t* _file_name = nullptr;
	_file_name = (wchar_t*)malloc(1024);
	wcscpy_s(_file_name, 256, file_name);
	int file_name_len = wcslen (_file_name);
	_file_name +=file_name_len ;

	wchar_t *file_ext = nullptr;
	for(int i =0 ; i <file_name_len ; i ++)
	{
		if(* _file_name == '.' )
		{
			file_ext = _file_name +1 ;
			break;
		}
		_file_name --;
	}
	return file_ext ;
}

NNSound::NNSound()
	: m_Playing(false)
{
}
NNSound::~NNSound()
{
	Destroy();
}

void NNSound::Create( std::wstring path )
{
	MCI_OPEN_PARMS mciOpen = {0};
	MCIERROR mciError = {0};

	if(wcscmp(GetFileExtenstion(path.c_str()), L"mp3") == 0 )
	{
		//mp3
		mciOpen.lpstrDeviceType = L"MPEGVideo";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	else if(wcscmp(GetFileExtenstion(path.c_str()), L"wav") == 0 )
	{
		mciOpen.lpstrDeviceType = L"waveaudio";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	mciOpen.lpstrElementName = path.c_str();

	mciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );
	if ( mciError )
	{
		return;
	}

	m_MciDevice = mciOpen.wDeviceID;
	m_Playing = false;
}

void NNSound::Destroy()
{
	if ( m_Playing )
	{
		Stop();
	}
	if ( m_MciDevice )
	{
		mciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );
	}
}

void NNSound::Play()
{
	if ( !m_MciDevice )
	{
		return;
	}
	MCI_PLAY_PARMS mciPlay = {0};
	MCIERROR mciError = {0};

	mciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();
	mciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );
	if ( !mciError )
	{
		m_Playing = true;
	}
}
void NNSound::Pause()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );
}
void NNSound::Resume()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );
}
void NNSound::Stop()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );
	m_Playing = false;
}

<|endoftext|>


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

#include "voyager/core/tcp_monitor.h"
#include "voyager/util/logging.h"

namespace voyager {

TcpMonitor::TcpMonitor(int max_all_connections, int max_ip_connections)
    : kMaxAllConnections(max_all_connections),
      kMaxIpConnections(max_ip_connections) {}

TcpMonitor::~TcpMonitor() {}

bool TcpMonitor::OnConnection(const TcpConnectionPtr& p) {
  bool result = true;
  const std::string& ip = p->PeerSockAddr().Ip();
  mutex_.lock();
  if (++counter_ > kMaxAllConnections) {
    result = false;
    VOYAGER_LOG(WARN) << "the all connection size is " << counter_
                      << ", more than " << kMaxAllConnections
                      << ", so force to close it.";
  } else {
    auto it = ip_counter_.find(ip);
    if (it != ip_counter_.end()) {
      if (++(it->second) > kMaxIpConnections) {
        VOYAGER_LOG(WARN) << "the connection size of ip=" << ip << " is "
                          << it->second << ", more than " << kMaxIpConnections
                          << ", so force to close it.";
        result = false;
      }
    } else {
      ip_counter_.insert(std::make_pair(ip, 1));
    }
  }
  mutex_.unlock();

  if (!result) {
    p->ForceClose();
  }
  return result;
}

void TcpMonitor::OnClose(const TcpConnectionPtr& p) {
  const std::string& ip = p->PeerSockAddr().Ip();
  std::lock_guard<std::mutex> lock(mutex_);
  auto it = ip_counter_.find(ip);
  if (it != ip_counter_.end()) {
    if (--(it->second) <= 0) {
      ip_counter_.erase(it);
    }
  }
  --counter_;
}

}  // namespace voyager
<commit_msg>fix bug, init the counter in tcp monitor<commit_after>// Copyright (c) 2016 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "voyager/core/tcp_monitor.h"
#include "voyager/util/logging.h"

namespace voyager {

TcpMonitor::TcpMonitor(int max_all_connections, int max_ip_connections)
    : kMaxAllConnections(max_all_connections),
      kMaxIpConnections(max_ip_connections),
      counter_(0) {}

TcpMonitor::~TcpMonitor() {}

bool TcpMonitor::OnConnection(const TcpConnectionPtr& p) {
  bool result = true;
  const std::string& ip = p->PeerSockAddr().Ip();
  mutex_.lock();
  if (++counter_ > kMaxAllConnections) {
    result = false;
    VOYAGER_LOG(WARN) << "the all connection size is " << counter_
                      << ", more than " << kMaxAllConnections
                      << ", so force to close it.";
  } else {
    auto it = ip_counter_.find(ip);
    if (it != ip_counter_.end()) {
      if (++(it->second) > kMaxIpConnections) {
        VOYAGER_LOG(WARN) << "the connection size of ip=" << ip << " is "
                          << it->second << ", more than " << kMaxIpConnections
                          << ", so force to close it.";
        result = false;
      }
    } else {
      ip_counter_.insert(std::make_pair(ip, 1));
    }
  }
  mutex_.unlock();

  if (!result) {
    p->ForceClose();
  }
  return result;
}

void TcpMonitor::OnClose(const TcpConnectionPtr& p) {
  const std::string& ip = p->PeerSockAddr().Ip();
  std::lock_guard<std::mutex> lock(mutex_);
  auto it = ip_counter_.find(ip);
  if (it != ip_counter_.end()) {
    if (--(it->second) <= 0) {
      ip_counter_.erase(it);
    }
  }
  --counter_;
}

}  // namespace voyager
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ContentInfo.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 06:14:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONTENT_INFO_HXX_
#define _CONTENT_INFO_HXX_

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEl_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#include <ZipPackageFolder.hxx>
#endif
#ifndef _ZIP_PACKAGE_STREAM_HXX
#include <ZipPackageStream.hxx>
#endif

namespace com { namespace sun { namespace star { namespace packages {
class ContentInfo : public cppu::OWeakObject
{
public:
    com::sun::star::uno::Reference < com::sun::star::lang::XUnoTunnel > xTunnel;
    bool bFolder;
    union
    {
        ZipPackageFolder *pFolder;
        ZipPackageStream *pStream;
    };
    ContentInfo ( ZipPackageStream * pNewStream )
    : xTunnel ( pNewStream )
    , bFolder ( false )
    , pStream ( pNewStream )
    {
    }
    ContentInfo ( ZipPackageFolder * pNewFolder )
    : xTunnel ( pNewFolder )
    , bFolder ( true )
    , pFolder ( pNewFolder )
    {
    }
    virtual ~ContentInfo ()
    {
        if ( bFolder )
            pFolder->releaseUpwardRef();
        else
            pStream->clearParent();
    }
};
} } } }
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.8.66); FILE MERGED 2008/04/01 12:32:14 thb 1.8.66.2: #i85898# Stripping all external header guards 2008/03/31 16:19:09 rt 1.8.66.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ContentInfo.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CONTENT_INFO_HXX_
#define _CONTENT_INFO_HXX_

#include <com/sun/star/container/XNameContainer.hpp>
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEl_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#include <ZipPackageFolder.hxx>
#include <ZipPackageStream.hxx>

namespace com { namespace sun { namespace star { namespace packages {
class ContentInfo : public cppu::OWeakObject
{
public:
    com::sun::star::uno::Reference < com::sun::star::lang::XUnoTunnel > xTunnel;
    bool bFolder;
    union
    {
        ZipPackageFolder *pFolder;
        ZipPackageStream *pStream;
    };
    ContentInfo ( ZipPackageStream * pNewStream )
    : xTunnel ( pNewStream )
    , bFolder ( false )
    , pStream ( pNewStream )
    {
    }
    ContentInfo ( ZipPackageFolder * pNewFolder )
    : xTunnel ( pNewFolder )
    , bFolder ( true )
    , pFolder ( pNewFolder )
    {
    }
    virtual ~ContentInfo ()
    {
        if ( bFolder )
            pFolder->releaseUpwardRef();
        else
            pStream->clearParent();
    }
};
} } } }
#endif
<|endoftext|>