<commit_before>/*************************************************************************
 *
 *  $RCSfile: forbiddencharacterstable.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: mt $ $Date: 2001-03-09 16:48:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <forbiddencharacterstable.hxx>

#include <unotools/localedatawrapper.hxx>
#include <unolingu.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

SvxForbiddenCharactersTable::SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize, USHORT nGrow )
 : SvxForbiddenCharactersTableImpl( nISize, nGrow )
{
    mxMSF = xMSF;
}

SvxForbiddenCharactersTable::~SvxForbiddenCharactersTable()
{
    for ( ULONG n = Count(); n; )
        delete GetObject( --n );
}

const com::sun::star::i18n::ForbiddenCharacters* SvxForbiddenCharactersTable::GetForbiddenCharacters( USHORT nLanguage, BOOL bGetDefault ) const
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf && bGetDefault && mxMSF.is() )
    {
        pInf = new ForbiddenCharactersInfo;
        ((SvxForbiddenCharactersTableImpl*)this)->Insert( nLanguage, pInf );
        pInf->bTemporary = TRUE;
        LocaleDataWrapper aWrapper( mxMSF, SvxCreateLocale( nLanguage ) );
        pInf->aForbiddenChars = aWrapper.getForbiddenCharacters();
    }
    return pInf ? &pInf->aForbiddenChars : NULL;
}

void SvxForbiddenCharactersTable::SetForbiddenCharacters( USHORT nLanguage, const com::sun::star::i18n::ForbiddenCharacters& rForbiddenChars )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf )
    {
        pInf = new ForbiddenCharactersInfo;
        Insert( nLanguage, pInf );
    }
    pInf->bTemporary = FALSE;
    pInf->aForbiddenChars = rForbiddenChars;
}

void SvxForbiddenCharactersTable::ClearForbiddenCharacters( USHORT nLanguage )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( pInf )
    {
        Remove( nLanguage );
        delete pInf;
    }
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1662); FILE MERGED 2005/09/05 14:23:58 rt 1.1.1662.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: forbiddencharacterstable.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:32:46 $
 *
 *  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
 *
 ************************************************************************/

#include <forbiddencharacterstable.hxx>

#include <unotools/localedatawrapper.hxx>
#include <unolingu.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

SvxForbiddenCharactersTable::SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize, USHORT nGrow )
 : SvxForbiddenCharactersTableImpl( nISize, nGrow )
{
    mxMSF = xMSF;
}

SvxForbiddenCharactersTable::~SvxForbiddenCharactersTable()
{
    for ( ULONG n = Count(); n; )
        delete GetObject( --n );
}

const com::sun::star::i18n::ForbiddenCharacters* SvxForbiddenCharactersTable::GetForbiddenCharacters( USHORT nLanguage, BOOL bGetDefault ) const
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf && bGetDefault && mxMSF.is() )
    {
        pInf = new ForbiddenCharactersInfo;
        ((SvxForbiddenCharactersTableImpl*)this)->Insert( nLanguage, pInf );
        pInf->bTemporary = TRUE;
        LocaleDataWrapper aWrapper( mxMSF, SvxCreateLocale( nLanguage ) );
        pInf->aForbiddenChars = aWrapper.getForbiddenCharacters();
    }
    return pInf ? &pInf->aForbiddenChars : NULL;
}

void SvxForbiddenCharactersTable::SetForbiddenCharacters( USHORT nLanguage, const com::sun::star::i18n::ForbiddenCharacters& rForbiddenChars )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf )
    {
        pInf = new ForbiddenCharactersInfo;
        Insert( nLanguage, pInf );
    }
    pInf->bTemporary = FALSE;
    pInf->aForbiddenChars = rForbiddenChars;
}

void SvxForbiddenCharactersTable::ClearForbiddenCharacters( USHORT nLanguage )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( pInf )
    {
        Remove( nLanguage );
        delete pInf;
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "syzygy/experimental/pdb_dumper/pdb_type_dump.h"

#include <algorithm>

#include "base/logging.h"
#include "syzygy/experimental/pdb_dumper/pdb_dump_util.h"
#include "syzygy/refinery/types/pdb_crawler.h"

namespace pdb {

namespace {

const char kUsage[] =
    "Usage: pdb_type_dump [options] <PDB file>...\n"
    "  Dumps information from type info stream in supplied PDB file as parsed\n"
    "  by PDB crawler.\n"
    "\n"
    "  Optional Options:\n"
    "    --dump-in-order if provided the types will be output ordered by\n"
    "       their type indices.\n"
    "    --dump-all-names if provided the names will be listed for all types\n"
    "       including function signatures which makes the output large.\n";

const char* GetTypeKindName(refinery::Type::TypeKind kind) {
  switch (kind) {
    case refinery::Type::USER_DEFINED_TYPE_KIND:
      return "USER_DEFINED_TYPE_KIND";
    case refinery::Type::BASIC_TYPE_KIND:
      return "BASIC_TYPE_KIND";
    case refinery::Type::POINTER_TYPE_KIND:
      return "POINTER_TYPE_KIND";
    case refinery::Type::FUNCTION_TYPE_KIND:
      return "FUNCTION_TYPE_KIND";
    case refinery::Type::ARRAY_TYPE_KIND:
      return "ARRAY_TYPE_KIND";
    case refinery::Type::WILDCARD_TYPE_KIND:
      return "WILDCARD_TYPE_KIND";
  }
  return "";
}

const char* GetCallConventionName(refinery::FunctionType::CallConvention call) {
  switch (call) {
    case refinery::FunctionType::CALL_NEAR_C:
      return "CALL_NEAR_C";
    case refinery::FunctionType::CALL_FAR_C:
      return "CALL_FAR_C";
    case refinery::FunctionType::CALL_NEAR_PASCAL:
      return "CALL_NEAR_PASCAL";
    case refinery::FunctionType::CALL_FAR_PASCAL:
      return "CALL_FAR_PASCAL";
    case refinery::FunctionType::CALL_NEAR_STDCALL:
      return "CALL_NEAR_STDCALL";
    case refinery::FunctionType::CALL_FAR_STDCALL:
      return "CALL_FAR_STDCALL";
    case refinery::FunctionType::CALL_THIS_CALL:
      return "CALL_THIS_CALL";
    case refinery::FunctionType::CALL_MIPS_CALL:
      return "CALL_MIPS_CALL";
    case refinery::FunctionType::CALL_GENERIC:
      return "CALL_GENERIC";
    case refinery::FunctionType::CALL_ALPHACALL:
      return "CALL_ALPHACALL";
    case refinery::FunctionType::CALL_PPCCALL:
      return "CALL_PPCCALL";
    case refinery::FunctionType::CALL_SHCALL:
      return "CALL_SHCALL";
    case refinery::FunctionType::CALL_ARMCALL:
      return "CALL_ARMCALL";
    case refinery::FunctionType::CALL_AM33CALL:
      return "CALL_AM33CALL";
    case refinery::FunctionType::CALL_TRICALL:
      return "CALL_TRICALL";
    case refinery::FunctionType::CALL_SH5CALL:
      return "CALL_SH5CALL";
    case refinery::FunctionType::CALL_M32RCALL:
      return "CALL_M32RCALL";
    case refinery::FunctionType::CALL_CLRCALL:
      return "CALL_CLRCALL";
  }
  return "";
}

}  // namespace

PdbTypeDumpApp::PdbTypeDumpApp()
    : application::AppImplBase("PDB Type Dumper"), dump_in_order_(false) {
}

bool PdbTypeDumpApp::ParseCommandLine(const base::CommandLine* command_line) {
  DCHECK(command_line != nullptr);

  base::CommandLine::StringVector args = command_line->GetArgs();
  if (args.size() != 1U)
    return Usage("You must provide one input file.");

  pdb_path_ = base::FilePath(args[0]);
  dump_in_order_ = command_line->HasSwitch("dump-in-order");
  dump_all_names_ = command_line->HasSwitch("dump-all-names");
  return true;
}

void PdbTypeDumpApp::DumpFlags(bool is_const,
                               bool is_volatile,
                               uint8_t indent_level) {
  if (is_const)
    DumpIndentedText(out(), indent_level, "is const.\n");
  if (is_volatile)
    DumpIndentedText(out(), indent_level, "is volatile.\n");
}

void PdbTypeDumpApp::DumpField(const refinery::UserDefinedType::Field& field,
                               uint8_t indent_level) {
  DumpIndentedText(out(), indent_level, "Field name: %S\n",
                   field.name().c_str());

  DumpIndentedText(out(), indent_level + 1, "Offset: %d\n", field.offset());
  DumpIndentedText(out(), indent_level + 1, "Properties:\n", field);
  DumpFlags(field.is_const(), field.is_volatile(), indent_level + 2);

  if (field.bit_len() != 0) {
    DumpIndentedText(out(), indent_level + 1, "Bit position: %d\n",
                     field.bit_pos());
    DumpIndentedText(out(), indent_level + 1, "Bit length: %d\n",
                     field.bit_len());
  }

  DumpIndentedText(out(), indent_level + 1, "Field type ID: %d\n",
                   field.type_id());
}

void PdbTypeDumpApp::DumpFunction(
    const refinery::UserDefinedType::Function& function,
    uint8_t indent_level) {
  DumpIndentedText(out(), indent_level, "Function name: %S\n",
                   function.name().c_str());
  DumpIndentedText(out(), indent_level + 1, "Function type ID: %d\n",
                   function.type_id());
}

void PdbTypeDumpApp::DumpArgument(refinery::FunctionType::ArgumentType argument,
                                  uint8_t indent_level) {
  DumpIndentedText(out(), indent_level, "Properties:\n");
  DumpFlags(argument.is_const(), argument.is_volatile(), indent_level + 1);
  DumpIndentedText(out(), indent_level, "Argument type ID: %d\n",
                   argument.type_id());
}

void PdbTypeDumpApp::DumpNames(refinery::TypePtr type, uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Name: %S\n", type->name().c_str());
  DumpIndentedText(out(), indent_level, "Decorated name: %S\n",
                   type->decorated_name().c_str());
}

void PdbTypeDumpApp::DumpBasicType(refinery::TypePtr type,
                                   uint8_t indent_level) {
  DCHECK(type != nullptr);

  // Always print names of basic types.
  DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpUserDefinedType(refinery::UserDefinedTypePtr type,
                                         uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "%d member fields:\n",
                   type->fields().size());
  for (const auto& field : type->fields())
    DumpField(field, indent_level + 1);

  DumpIndentedText(out(), indent_level, "%d member functions:\n",
                   type->functions().size());
  for (const auto& function : type->functions())
    DumpFunction(function, indent_level + 1);

  // Always print names of user defined types.
  DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpArrayType(refinery::ArrayTypePtr type,
                                   uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Properties:\n");
  DumpFlags(type->is_const(), type->is_volatile(), indent_level + 1);

  DumpIndentedText(out(), indent_level, "Number of elements: %d\n",
                   type->num_elements());
  DumpIndentedText(out(), indent_level, "Index type ID: %d\n",
                   type->index_type_id());
  DumpIndentedText(out(), indent_level, "Element type ID: %d\n",
                   type->element_type_id());

  if (dump_all_names_)
    DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpPointerType(refinery::PointerTypePtr type,
                                     uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Properties:\n");

  if (type->ptr_mode() == refinery::PointerType::PTR_MODE_REF)
    DumpIndentedText(out(), indent_level + 1, "is a reference.\n");

  DumpFlags(type->is_const(), type->is_volatile(), indent_level + 1);

  DumpIndentedText(out(), indent_level + 1, "Content type ID: %d\n",
                   type->content_type_id());

  if (dump_all_names_)
    DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpFunctionType(refinery::FunctionTypePtr type,
                                      uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Call convention: %s\n",
                   GetCallConventionName(type->call_convention()));

  if (type->IsMemberFunction()) {
    DumpIndentedText(out(), indent_level, "This is a member function.\n");
    DumpIndentedText(out(), indent_level + 1, "Containing class type ID: %d\n",
                     type->containing_class_id());
  }

  DumpIndentedText(out(), indent_level, "Return type:\n");
  DumpArgument(type->return_type(), indent_level + 1);

  DumpIndentedText(out(), indent_level, "%d arguments:\n",
                   type->argument_types().size());
  for (const auto& arg : type->argument_types())
    DumpArgument(arg, indent_level + 1);

  if (dump_all_names_)
    DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpType(refinery::TypePtr type, uint8_t indent_level) {
  DCHECK(type != nullptr);

  // Dump common properties.
  DumpIndentedText(out(), indent_level, "Type ID %d:\n", type->type_id());
  DumpIndentedText(out(), indent_level + 1, "Type kind: %s\n",
                   GetTypeKindName(type->kind()));
  DumpIndentedText(out(), indent_level + 1, "Size: %d\n", type->size());

  switch (type->kind()) {
    case refinery::Type::USER_DEFINED_TYPE_KIND: {
      refinery::UserDefinedTypePtr udt;
      type->CastTo(&udt);
      DumpUserDefinedType(udt, indent_level + 1);
      break;
    }
    case refinery::Type::ARRAY_TYPE_KIND: {
      refinery::ArrayTypePtr array_type;
      type->CastTo(&array_type);
      DumpArrayType(array_type, indent_level + 1);
      break;
    }
    case refinery::Type::POINTER_TYPE_KIND: {
      refinery::PointerTypePtr ptr_type;
      type->CastTo(&ptr_type);
      DumpPointerType(ptr_type, indent_level + 1);
      break;
    }
    case refinery::Type::FUNCTION_TYPE_KIND: {
      refinery::FunctionTypePtr fcn_type;
      type->CastTo(&fcn_type);
      DumpFunctionType(fcn_type, indent_level + 1);
      break;
    }
    case refinery::Type::BASIC_TYPE_KIND:
    case refinery::Type::WILDCARD_TYPE_KIND: {
      DumpBasicType(type, indent_level);
      break;
    }
  }
}

int PdbTypeDumpApp::Run() {
  refinery::PdbCrawler crawler;
  refinery::TypeRepository repository;

  // Load the types.
  if (!crawler.InitializeForFile(pdb_path_))
    return 1;

  if (!crawler.GetTypes(&repository))
    return 1;

  DumpIndentedText(out(), 0, "%d types parsed from the PDB stream:\n",
                   repository.size());

  if (dump_in_order_) {
    // We need to sort the repository.
    std::vector<refinery::TypePtr> ordered_repository(repository.begin(),
                                                      repository.end());
    std::sort(ordered_repository.begin(), ordered_repository.end(),
              [](const refinery::TypePtr& a, const refinery::TypePtr& b)
                  -> bool { return a->type_id() < b->type_id(); });

    for (refinery::TypePtr type : ordered_repository) {
      DumpType(type, 1);
    }
  } else {
    for (refinery::TypePtr type : repository) {
      DumpType(type, 1);
    }
  }

  return 0;
}

bool PdbTypeDumpApp::Usage(const char* message) {
  ::fprintf(err(), "%s\n%s", message, kUsage);
  return false;
}

}  // namespace pdb
<commit_msg>PdbTypeDumper: Dump forward declaration flag of UDT<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "syzygy/experimental/pdb_dumper/pdb_type_dump.h"

#include <algorithm>

#include "base/logging.h"
#include "syzygy/experimental/pdb_dumper/pdb_dump_util.h"
#include "syzygy/refinery/types/pdb_crawler.h"

namespace pdb {

namespace {

const char kUsage[] =
    "Usage: pdb_type_dump [options] <PDB file>...\n"
    "  Dumps information from type info stream in supplied PDB file as parsed\n"
    "  by PDB crawler.\n"
    "\n"
    "  Optional Options:\n"
    "    --dump-in-order if provided the types will be output ordered by\n"
    "       their type indices.\n"
    "    --dump-all-names if provided the names will be listed for all types\n"
    "       including function signatures which makes the output large.\n";

const char* GetTypeKindName(refinery::Type::TypeKind kind) {
  switch (kind) {
    case refinery::Type::USER_DEFINED_TYPE_KIND:
      return "USER_DEFINED_TYPE_KIND";
    case refinery::Type::BASIC_TYPE_KIND:
      return "BASIC_TYPE_KIND";
    case refinery::Type::POINTER_TYPE_KIND:
      return "POINTER_TYPE_KIND";
    case refinery::Type::FUNCTION_TYPE_KIND:
      return "FUNCTION_TYPE_KIND";
    case refinery::Type::ARRAY_TYPE_KIND:
      return "ARRAY_TYPE_KIND";
    case refinery::Type::WILDCARD_TYPE_KIND:
      return "WILDCARD_TYPE_KIND";
  }
  return "";
}

const char* GetCallConventionName(refinery::FunctionType::CallConvention call) {
  switch (call) {
    case refinery::FunctionType::CALL_NEAR_C:
      return "CALL_NEAR_C";
    case refinery::FunctionType::CALL_FAR_C:
      return "CALL_FAR_C";
    case refinery::FunctionType::CALL_NEAR_PASCAL:
      return "CALL_NEAR_PASCAL";
    case refinery::FunctionType::CALL_FAR_PASCAL:
      return "CALL_FAR_PASCAL";
    case refinery::FunctionType::CALL_NEAR_STDCALL:
      return "CALL_NEAR_STDCALL";
    case refinery::FunctionType::CALL_FAR_STDCALL:
      return "CALL_FAR_STDCALL";
    case refinery::FunctionType::CALL_THIS_CALL:
      return "CALL_THIS_CALL";
    case refinery::FunctionType::CALL_MIPS_CALL:
      return "CALL_MIPS_CALL";
    case refinery::FunctionType::CALL_GENERIC:
      return "CALL_GENERIC";
    case refinery::FunctionType::CALL_ALPHACALL:
      return "CALL_ALPHACALL";
    case refinery::FunctionType::CALL_PPCCALL:
      return "CALL_PPCCALL";
    case refinery::FunctionType::CALL_SHCALL:
      return "CALL_SHCALL";
    case refinery::FunctionType::CALL_ARMCALL:
      return "CALL_ARMCALL";
    case refinery::FunctionType::CALL_AM33CALL:
      return "CALL_AM33CALL";
    case refinery::FunctionType::CALL_TRICALL:
      return "CALL_TRICALL";
    case refinery::FunctionType::CALL_SH5CALL:
      return "CALL_SH5CALL";
    case refinery::FunctionType::CALL_M32RCALL:
      return "CALL_M32RCALL";
    case refinery::FunctionType::CALL_CLRCALL:
      return "CALL_CLRCALL";
  }
  return "";
}

}  // namespace

PdbTypeDumpApp::PdbTypeDumpApp()
    : application::AppImplBase("PDB Type Dumper"), dump_in_order_(false) {
}

bool PdbTypeDumpApp::ParseCommandLine(const base::CommandLine* command_line) {
  DCHECK(command_line != nullptr);

  base::CommandLine::StringVector args = command_line->GetArgs();
  if (args.size() != 1U)
    return Usage("You must provide one input file.");

  pdb_path_ = base::FilePath(args[0]);
  dump_in_order_ = command_line->HasSwitch("dump-in-order");
  dump_all_names_ = command_line->HasSwitch("dump-all-names");
  return true;
}

void PdbTypeDumpApp::DumpFlags(bool is_const,
                               bool is_volatile,
                               uint8_t indent_level) {
  if (is_const)
    DumpIndentedText(out(), indent_level, "is const.\n");
  if (is_volatile)
    DumpIndentedText(out(), indent_level, "is volatile.\n");
}

void PdbTypeDumpApp::DumpField(const refinery::UserDefinedType::Field& field,
                               uint8_t indent_level) {
  DumpIndentedText(out(), indent_level, "Field name: %S\n",
                   field.name().c_str());

  DumpIndentedText(out(), indent_level + 1, "Offset: %d\n", field.offset());
  DumpIndentedText(out(), indent_level + 1, "Properties:\n", field);
  DumpFlags(field.is_const(), field.is_volatile(), indent_level + 2);

  if (field.bit_len() != 0) {
    DumpIndentedText(out(), indent_level + 1, "Bit position: %d\n",
                     field.bit_pos());
    DumpIndentedText(out(), indent_level + 1, "Bit length: %d\n",
                     field.bit_len());
  }

  DumpIndentedText(out(), indent_level + 1, "Field type ID: %d\n",
                   field.type_id());
}

void PdbTypeDumpApp::DumpFunction(
    const refinery::UserDefinedType::Function& function,
    uint8_t indent_level) {
  DumpIndentedText(out(), indent_level, "Function name: %S\n",
                   function.name().c_str());
  DumpIndentedText(out(), indent_level + 1, "Function type ID: %d\n",
                   function.type_id());
}

void PdbTypeDumpApp::DumpArgument(refinery::FunctionType::ArgumentType argument,
                                  uint8_t indent_level) {
  DumpIndentedText(out(), indent_level, "Properties:\n");
  DumpFlags(argument.is_const(), argument.is_volatile(), indent_level + 1);
  DumpIndentedText(out(), indent_level, "Argument type ID: %d\n",
                   argument.type_id());
}

void PdbTypeDumpApp::DumpNames(refinery::TypePtr type, uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Name: %S\n", type->name().c_str());
  DumpIndentedText(out(), indent_level, "Decorated name: %S\n",
                   type->decorated_name().c_str());
}

void PdbTypeDumpApp::DumpBasicType(refinery::TypePtr type,
                                   uint8_t indent_level) {
  DCHECK(type != nullptr);

  // Always print names of basic types.
  DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpUserDefinedType(refinery::UserDefinedTypePtr type,
                                         uint8_t indent_level) {
  DCHECK(type != nullptr);

  if (type->is_fwd_decl()) {
    DumpIndentedText(out(), indent_level,
                     "This is only forward declaration.\n");
  }

  DumpIndentedText(out(), indent_level, "%d member fields:\n",
                   type->fields().size());
  for (const auto& field : type->fields())
    DumpField(field, indent_level + 1);

  DumpIndentedText(out(), indent_level, "%d member functions:\n",
                   type->functions().size());
  for (const auto& function : type->functions())
    DumpFunction(function, indent_level + 1);

  // Always print names of user defined types.
  DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpArrayType(refinery::ArrayTypePtr type,
                                   uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Properties:\n");
  DumpFlags(type->is_const(), type->is_volatile(), indent_level + 1);

  DumpIndentedText(out(), indent_level, "Number of elements: %d\n",
                   type->num_elements());
  DumpIndentedText(out(), indent_level, "Index type ID: %d\n",
                   type->index_type_id());
  DumpIndentedText(out(), indent_level, "Element type ID: %d\n",
                   type->element_type_id());

  if (dump_all_names_)
    DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpPointerType(refinery::PointerTypePtr type,
                                     uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Properties:\n");

  if (type->ptr_mode() == refinery::PointerType::PTR_MODE_REF)
    DumpIndentedText(out(), indent_level + 1, "is a reference.\n");

  DumpFlags(type->is_const(), type->is_volatile(), indent_level + 1);

  DumpIndentedText(out(), indent_level + 1, "Content type ID: %d\n",
                   type->content_type_id());

  if (dump_all_names_)
    DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpFunctionType(refinery::FunctionTypePtr type,
                                      uint8_t indent_level) {
  DCHECK(type != nullptr);

  DumpIndentedText(out(), indent_level, "Call convention: %s\n",
                   GetCallConventionName(type->call_convention()));

  if (type->IsMemberFunction()) {
    DumpIndentedText(out(), indent_level, "This is a member function.\n");
    DumpIndentedText(out(), indent_level + 1, "Containing class type ID: %d\n",
                     type->containing_class_id());
  }

  DumpIndentedText(out(), indent_level, "Return type:\n");
  DumpArgument(type->return_type(), indent_level + 1);

  DumpIndentedText(out(), indent_level, "%d arguments:\n",
                   type->argument_types().size());
  for (const auto& arg : type->argument_types())
    DumpArgument(arg, indent_level + 1);

  if (dump_all_names_)
    DumpNames(type, indent_level);
}

void PdbTypeDumpApp::DumpType(refinery::TypePtr type, uint8_t indent_level) {
  DCHECK(type != nullptr);

  // Dump common properties.
  DumpIndentedText(out(), indent_level, "Type ID %d:\n", type->type_id());
  DumpIndentedText(out(), indent_level + 1, "Type kind: %s\n",
                   GetTypeKindName(type->kind()));
  DumpIndentedText(out(), indent_level + 1, "Size: %d\n", type->size());

  switch (type->kind()) {
    case refinery::Type::USER_DEFINED_TYPE_KIND: {
      refinery::UserDefinedTypePtr udt;
      type->CastTo(&udt);
      DumpUserDefinedType(udt, indent_level + 1);
      break;
    }
    case refinery::Type::ARRAY_TYPE_KIND: {
      refinery::ArrayTypePtr array_type;
      type->CastTo(&array_type);
      DumpArrayType(array_type, indent_level + 1);
      break;
    }
    case refinery::Type::POINTER_TYPE_KIND: {
      refinery::PointerTypePtr ptr_type;
      type->CastTo(&ptr_type);
      DumpPointerType(ptr_type, indent_level + 1);
      break;
    }
    case refinery::Type::FUNCTION_TYPE_KIND: {
      refinery::FunctionTypePtr fcn_type;
      type->CastTo(&fcn_type);
      DumpFunctionType(fcn_type, indent_level + 1);
      break;
    }
    case refinery::Type::BASIC_TYPE_KIND:
    case refinery::Type::WILDCARD_TYPE_KIND: {
      DumpBasicType(type, indent_level);
      break;
    }
  }
}

int PdbTypeDumpApp::Run() {
  refinery::PdbCrawler crawler;
  refinery::TypeRepository repository;

  // Load the types.
  if (!crawler.InitializeForFile(pdb_path_))
    return 1;

  if (!crawler.GetTypes(&repository))
    return 1;

  DumpIndentedText(out(), 0, "%d types parsed from the PDB stream:\n",
                   repository.size());

  if (dump_in_order_) {
    // We need to sort the repository.
    std::vector<refinery::TypePtr> ordered_repository(repository.begin(),
                                                      repository.end());
    std::sort(ordered_repository.begin(), ordered_repository.end(),
              [](const refinery::TypePtr& a, const refinery::TypePtr& b)
                  -> bool { return a->type_id() < b->type_id(); });

    for (refinery::TypePtr type : ordered_repository) {
      DumpType(type, 1);
    }
  } else {
    for (refinery::TypePtr type : repository) {
      DumpType(type, 1);
    }
  }

  return 0;
}

bool PdbTypeDumpApp::Usage(const char* message) {
  ::fprintf(err(), "%s\n%s", message, kUsage);
  return false;
}

}  // namespace pdb
<|endoftext|>


<commit_before>// Copyright 2016 AUV-IITK
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "ros/ros.h"
#include "std_msgs/Float64.h"
#include <fstream>
#include <vector>
#include <cv.h>
#include <highgui.h>
#include "std_msgs/String.h"
#include "std_msgs/Int8.h"
#include <std_msgs/Bool.h>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <image_transport/image_transport.h>
#include <task_line/lineConfig.h>
#include <dynamic_reconfigure/server.h>
#include "std_msgs/Float64MultiArray.h"
#include <cv_bridge/cv_bridge.h>
#include <sstream>
#include <string>
#include "std_msgs/Header.h"
using cv::Mat;
using cv::split;
using cv::Size;
using cv::Scalar;
using cv::normalize;
using cv::Point;
using cv::VideoCapture;
using cv::NORM_MINMAX;
using cv::MORPH_ELLIPSE;
using cv::COLOR_BGR2HSV;
using cv::destroyAllWindows;
using cv::getStructuringElement;
using cv::Vec4i;
using cv::namedWindow;
using std::vector;
using std::endl;
using std::cout;

int w = -2, x = -2, y = -2, z = -2, m = -1;
bool IP = true;
bool flag = false;
bool video = false;
int t1min, t1max, t2min, t2max, t3min, t3max, lineCount = 0;

void callback_dyn(task_line::lineConfig &config, uint32_t level)
{
  t1min = config.t1min_param;
  t1max = config.t1max_param;
  t2min = config.t2min_param;
  t2max = config.t2max_param;
  t3min = config.t3min_param;
  t3max = config.t3max_param;
  ROS_INFO("Line_angle Reconfigure: New params: %d %d %d %d %d %d ", t1min, t1max, t2min, t2max, t3min, t3max);
}

std_msgs::Float64 msg;
// parameters in param file should be nearly the same as the commented values
// params for an orange strip
int LowH = 0;    // 0
int HighH = 88;  // 88

int LowS = 0;     // 0
int HighS = 251;  // 251

int LowV = 0;     // 0
int HighV = 255;  // 255

// params for hough line transform
int lineThresh = 60;     // 60
int minLineLength = 70;  // 70
int maxLineGap = 10;     // 10
int houghThresh = 15;    // 15

double rho = 0.1;
double finalAngle = -1;
double minDeviation = 0.02;

cv::Mat frame;
cv::Mat newframe, sent_to_callback, imgLines;
int count = 0, count_avg = 0;

double computeMean(vector<double> &newAngles)
{
  double sum = 0;
  for (size_t i = 0; i < newAngles.size(); i++)
  {
    sum = sum + newAngles[i];
  }
  return sum / newAngles.size();
}
// called when few lines are detected
// to remove errors due to any stray results
double computeMode(vector<double> &newAngles)
{
  double mode = newAngles[0];
  int freq = 1;
  int tempFreq;
  double diff;
  for (int i = 0; i < newAngles.size(); i++)
  {
    tempFreq = 1;

    for (int j = i + 1; j < newAngles.size(); j++)
    {
      diff = newAngles[j] - newAngles[i] > 0.0 ? newAngles[j] - newAngles[i] : newAngles[i] - newAngles[j];
      if (diff <= minDeviation)
      {
        tempFreq++;
        newAngles.erase(newAngles.begin() + j);
        j = j - 1;
      }
    }

    if (tempFreq >= freq)
    {
      mode = newAngles[i];
      freq = tempFreq;
    }
  }

  return mode;
}

void callback(int, void *)
{
  vector<Vec4i> lines;
  HoughLinesP(sent_to_callback, lines, 1, CV_PI / 180, lineThresh, minLineLength, maxLineGap);

  frame.copyTo(imgLines);
  imgLines = Scalar(0, 0, 0);
  vector<double> angles(lines.size());

  lineCount = lines.size();
  int j = 0;
  for (size_t i = 0; i < lines.size(); i++)
  {
    Vec4i l = lines[i];
    line(imgLines, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 255, 0), 1, CV_AA);
    if ((l[2] == l[0]) || (l[1] == l[3]))
      continue;
    angles[j] = atan(static_cast<double>(l[2] - l[0]) / (l[1] - l[3]));
    j++;
  }

  imshow("LINES", imgLines + frame);

  // if num of lines are large than one or two stray lines won't affect the mean
  // much
  // but if they are small in number than mode has to be taken to save the error
  // due to those stray line

  if (lines.size() > 0 && lines.size() < 10)
    finalAngle = computeMode(angles);
  else if (lines.size() > 0)
    finalAngle = computeMean(angles);
}

void lineAngleListener(std_msgs::Bool msg)
{
  IP = msg.data;
}

void imageCallback(const sensor_msgs::ImageConstPtr &msg)
{
  if (m == 32)
    return;
  try
  {
    count++;
    newframe = cv_bridge::toCvShare(msg, "bgr8")->image;
    cvNamedWindow("newframe", CV_WINDOW_NORMAL);
    ///////////////////////////// DO NOT REMOVE THIS, IT COULD BE INGERIOUS TO HEALTH /////////////////////
    newframe.copyTo(frame);
    cv::imshow("newframe", newframe);
    ////////////////////////// FATAL ///////////////////////////////////////////////////
  }
  catch (cv_bridge::Exception &e)
  {
    ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
  }
}

int main(int argc, char *argv[])
{
  int height, width, step, channels;  // parameters of the image we are working on
  std::string Video_Name = "Random_Video";
  if (argc >= 2)
    flag = true;
  if (argc == 3)
  {
    video = true;
    std::string avi = ".avi";
    Video_Name = (argv[2]) + avi;
  }

  cv::VideoWriter output_cap(Video_Name, CV_FOURCC('D', 'I', 'V', 'X'), 9, cv::Size(640, 480));

  ros::init(argc, argv, "gate_detection");
  ros::NodeHandle n;

  ros::Publisher pub = n.advertise<std_msgs::Float64>("/varun/ip/line_angle", 1000);
  ros::Subscriber sub = n.subscribe<std_msgs::Bool>("line_angle_switch", 1000, &lineAngleListener);
  ros::Rate loop_rate(10);

  image_transport::ImageTransport it(n);
  image_transport::Subscriber sub1 = it.subscribe("/varun/sensors/front_camera/image_raw", 1, imageCallback);

  n.getParam("line_angle/t1max", t1max);
  n.getParam("line_angle/t1min", t1min);
  n.getParam("line_angle/t2max", t2max);
  n.getParam("line_angle/t2min", t2min);
  n.getParam("line_angle/t3max", t3max);
  n.getParam("line_angle/t3min", t3min);

  dynamic_reconfigure::Server<task_line::lineConfig> server;
  dynamic_reconfigure::Server<task_line::lineConfig>::CallbackType f;
  f = boost::bind(&callback_dyn, _1, _2);
  server.setCallback(f);

  cvNamedWindow("After Color Filtering", CV_WINDOW_NORMAL);
  cvNamedWindow("Contours", CV_WINDOW_NORMAL);
  cvNamedWindow("LINES", CV_WINDOW_NORMAL);

  if (flag)
  {
    cvNamedWindow("F1", CV_WINDOW_NORMAL);
    cvNamedWindow("F2", CV_WINDOW_NORMAL);
    cvNamedWindow("F3", CV_WINDOW_NORMAL);

    cvCreateTrackbar("t1min", "F1", &t1min, 260, NULL);
    cvCreateTrackbar("t1max", "F1", &t1max, 260, NULL);
    cvCreateTrackbar("t2min", "F2", &t2min, 260, NULL);
    cvCreateTrackbar("t2max", "F2", &t2max, 260, NULL);
    cvCreateTrackbar("t3min", "F3", &t3min, 260, NULL);
    cvCreateTrackbar("t3max", "F3", &t3max, 260, NULL);
  }
  // capture size -
  CvSize size = cvSize(width, height);

  // Initialize different images that are going to be used in the program
  cv::Mat hsv_frame, thresholded, thresholded1, thresholded2, thresholded3, filtered;  // image converted to HSV plane
  // asking for the minimum distance where bwe fire torpedo

  while (ros::ok())
  {
    loop_rate.sleep();
    // Get one frame
    if (frame.empty())
    {
      ROS_INFO("%s: empty frame", ros::this_node::getName().c_str());
      ros::spinOnce();
      continue;
    }

    if (video)
      output_cap.write(frame);

    // get the image data
    height = frame.rows;
    width = frame.cols;
    step = frame.step;

    // Covert color space to HSV as it is much easier to filter colors in the HSV color-space.
    cv::cvtColor(frame, hsv_frame, CV_BGR2HSV);

    cv::Scalar hsv_min = cv::Scalar(t1min, t2min, t3min, 0);
    cv::Scalar hsv_max = cv::Scalar(t1max, t2max, t3max, 0);

    // Filter out colors which are out of range.
    cv::inRange(hsv_frame, hsv_min, hsv_max, thresholded);
    // Split image into its 3 one dimensional images
    cv::Mat thresholded_hsv[3];
    cv::split(hsv_frame, thresholded_hsv);

    // Filter out colors which are out of range.
    cv::inRange(thresholded_hsv[0], cv::Scalar(t1min, 0, 0, 0), cv::Scalar(t1max, 0, 0, 0), thresholded_hsv[0]);
    cv::inRange(thresholded_hsv[1], cv::Scalar(t2min, 0, 0, 0), cv::Scalar(t2max, 0, 0, 0), thresholded_hsv[1]);
    cv::inRange(thresholded_hsv[2], cv::Scalar(t3min, 0, 0, 0), cv::Scalar(t3max, 0, 0, 0), thresholded_hsv[2]);

    cv::GaussianBlur(thresholded, thresholded, cv::Size(9, 9), 0, 0, 0);
    cv::imshow("After Color Filtering", thresholded);  // The stream after color filtering

    if (flag)
    {
      cv::imshow("F1", thresholded_hsv[0]);  // individual filters
      cv::imshow("F2", thresholded_hsv[1]);
      cv::imshow("F3", thresholded_hsv[2]);
    }

    if ((cvWaitKey(10) & 255) == 27)
      break;

    if (!IP)
    {
      // find contours
      std::vector<std::vector<cv::Point> > contours;
      cv::Mat thresholded_Mat = thresholded;
      findContours(thresholded_Mat, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);  // Find the contours in the image
      double largest_area = 0, largest_contour_index = 0;
      if (contours.empty())
      {
        msg.data = -finalAngle * (180 / 3.14) + 90;
        pub.publish(msg);
        ros::spinOnce();
        // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
        // remove higher bits using AND operator
        if ((cvWaitKey(10) & 255) == 27)
          break;
        continue;
      }

      for (int i = 0; i < contours.size(); i++)  // iterate through each contour.
      {
        double a = contourArea(contours[i], false);  //  Find the area of contour
        if (a > largest_area)
        {
          largest_area = a;
          largest_contour_index = i;  // Store the index of largest contour
        }
      }
      // Convex HULL
      std::vector<std::vector<cv::Point> > hull(contours.size());
      convexHull(cv::Mat(contours[largest_contour_index]), hull[largest_contour_index], false);

      cv::Mat Drawing(thresholded_Mat.rows, thresholded_Mat.cols, CV_8UC1, cv::Scalar::all(0));
      std::vector<cv::Vec4i> hierarchy;
      cv::Scalar color(255, 255, 255);
      drawContours(Drawing, contours, largest_contour_index, color, 2, 8, hierarchy);
      cv::imshow("Contours", Drawing);

      std_msgs::Float64 msg;
      Drawing.copyTo(sent_to_callback);
      /*
      msg.data never takes positive 90
      when the angle is 90 it will show -90
      -------------TO BE CORRECTED-------------
      */
      msg.data = -finalAngle * (180 / 3.14);
      if (lineCount > 0)
      {
        pub.publish(msg);
      }
      callback(0, 0);  // for displaying the thresholded image initially
      ros::spinOnce();
      // loop_rate.sleep();

      // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
      // remove higher bits using AND operator
      if ((cvWaitKey(10) & 255) == 27)
        break;
      if ((cvWaitKey(10) & 255) == 32)
      {
        if (m == 32)
          m = -1;
        else
          m = 32;
      }
      if (m == 32)
        ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
      ros::spinOnce();
    }
    else
    {
      ROS_INFO("%s: waiting\n", ros::this_node::getName().c_str());
      if ((cvWaitKey(10) & 255) == 32)
      {
        if (m == 32)
          x = -1;
        else
          m = 32;
      }
      if (m == 32)
        ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
      ros::spinOnce();
    }
  }
  output_cap.release();
  return 0;
}
<commit_msg>chaged camera<commit_after>// Copyright 2016 AUV-IITK
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "ros/ros.h"
#include "std_msgs/Float64.h"
#include <fstream>
#include <vector>
#include <cv.h>
#include <highgui.h>
#include "std_msgs/String.h"
#include "std_msgs/Int8.h"
#include <std_msgs/Bool.h>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <image_transport/image_transport.h>
#include <task_line/lineConfig.h>
#include <dynamic_reconfigure/server.h>
#include "std_msgs/Float64MultiArray.h"
#include <cv_bridge/cv_bridge.h>
#include <sstream>
#include <string>
#include "std_msgs/Header.h"
using cv::Mat;
using cv::split;
using cv::Size;
using cv::Scalar;
using cv::normalize;
using cv::Point;
using cv::VideoCapture;
using cv::NORM_MINMAX;
using cv::MORPH_ELLIPSE;
using cv::COLOR_BGR2HSV;
using cv::destroyAllWindows;
using cv::getStructuringElement;
using cv::Vec4i;
using cv::namedWindow;
using std::vector;
using std::endl;
using std::cout;

int w = -2, x = -2, y = -2, z = -2, m = -1;
bool IP = true;
bool flag = false;
bool video = false;
int t1min, t1max, t2min, t2max, t3min, t3max, lineCount = 0;

void callback_dyn(task_line::lineConfig &config, uint32_t level)
{
  t1min = config.t1min_param;
  t1max = config.t1max_param;
  t2min = config.t2min_param;
  t2max = config.t2max_param;
  t3min = config.t3min_param;
  t3max = config.t3max_param;
  ROS_INFO("Line_angle Reconfigure: New params: %d %d %d %d %d %d ", t1min, t1max, t2min, t2max, t3min, t3max);
}

std_msgs::Float64 msg;
// parameters in param file should be nearly the same as the commented values
// params for an orange strip
int LowH = 0;    // 0
int HighH = 88;  // 88

int LowS = 0;     // 0
int HighS = 251;  // 251

int LowV = 0;     // 0
int HighV = 255;  // 255

// params for hough line transform
int lineThresh = 60;     // 60
int minLineLength = 70;  // 70
int maxLineGap = 10;     // 10
int houghThresh = 15;    // 15

double rho = 0.1;
double finalAngle = -1;
double minDeviation = 0.02;

cv::Mat frame;
cv::Mat newframe, sent_to_callback, imgLines;
int count = 0, count_avg = 0;

double computeMean(vector<double> &newAngles)
{
  double sum = 0;
  for (size_t i = 0; i < newAngles.size(); i++)
  {
    sum = sum + newAngles[i];
  }
  return sum / newAngles.size();
}
// called when few lines are detected
// to remove errors due to any stray results
double computeMode(vector<double> &newAngles)
{
  double mode = newAngles[0];
  int freq = 1;
  int tempFreq;
  double diff;
  for (int i = 0; i < newAngles.size(); i++)
  {
    tempFreq = 1;

    for (int j = i + 1; j < newAngles.size(); j++)
    {
      diff = newAngles[j] - newAngles[i] > 0.0 ? newAngles[j] - newAngles[i] : newAngles[i] - newAngles[j];
      if (diff <= minDeviation)
      {
        tempFreq++;
        newAngles.erase(newAngles.begin() + j);
        j = j - 1;
      }
    }

    if (tempFreq >= freq)
    {
      mode = newAngles[i];
      freq = tempFreq;
    }
  }

  return mode;
}

void callback(int, void *)
{
  vector<Vec4i> lines;
  HoughLinesP(sent_to_callback, lines, 1, CV_PI / 180, lineThresh, minLineLength, maxLineGap);

  frame.copyTo(imgLines);
  imgLines = Scalar(0, 0, 0);
  vector<double> angles(lines.size());

  lineCount = lines.size();
  int j = 0;
  for (size_t i = 0; i < lines.size(); i++)
  {
    Vec4i l = lines[i];
    line(imgLines, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 255, 0), 1, CV_AA);
    if ((l[2] == l[0]) || (l[1] == l[3]))
      continue;
    angles[j] = atan(static_cast<double>(l[2] - l[0]) / (l[1] - l[3]));
    j++;
  }

  imshow("LINES", imgLines + frame);

  // if num of lines are large than one or two stray lines won't affect the mean
  // much
  // but if they are small in number than mode has to be taken to save the error
  // due to those stray line

  if (lines.size() > 0 && lines.size() < 10)
    finalAngle = computeMode(angles);
  else if (lines.size() > 0)
    finalAngle = computeMean(angles);
}

void lineAngleListener(std_msgs::Bool msg)
{
  IP = msg.data;
}

void imageCallback(const sensor_msgs::ImageConstPtr &msg)
{
  if (m == 32)
    return;
  try
  {
    count++;
    newframe = cv_bridge::toCvShare(msg, "bgr8")->image;
    cvNamedWindow("newframe", CV_WINDOW_NORMAL);
    ///////////////////////////// DO NOT REMOVE THIS, IT COULD BE INGERIOUS TO HEALTH /////////////////////
    newframe.copyTo(frame);
    cv::imshow("newframe", newframe);
    ////////////////////////// FATAL ///////////////////////////////////////////////////
  }
  catch (cv_bridge::Exception &e)
  {
    ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
  }
}

int main(int argc, char *argv[])
{
  int height, width, step, channels;  // parameters of the image we are working on
  std::string Video_Name = "Random_Video";
  if (argc >= 2)
    flag = true;
  if (argc == 3)
  {
    video = true;
    std::string avi = ".avi";
    Video_Name = (argv[2]) + avi;
  }

  cv::VideoWriter output_cap(Video_Name, CV_FOURCC('D', 'I', 'V', 'X'), 9, cv::Size(640, 480));

  ros::init(argc, argv, "gate_detection");
  ros::NodeHandle n;

  ros::Publisher pub = n.advertise<std_msgs::Float64>("/varun/ip/line_angle", 1000);
  ros::Subscriber sub = n.subscribe<std_msgs::Bool>("line_angle_switch", 1000, &lineAngleListener);
  ros::Rate loop_rate(10);

  image_transport::ImageTransport it(n);
  image_transport::Subscriber sub1 = it.subscribe("/varun/sensors/bottom_camera/image_raw", 1, imageCallback);

  n.getParam("line_angle/t1max", t1max);
  n.getParam("line_angle/t1min", t1min);
  n.getParam("line_angle/t2max", t2max);
  n.getParam("line_angle/t2min", t2min);
  n.getParam("line_angle/t3max", t3max);
  n.getParam("line_angle/t3min", t3min);

  dynamic_reconfigure::Server<task_line::lineConfig> server;
  dynamic_reconfigure::Server<task_line::lineConfig>::CallbackType f;
  f = boost::bind(&callback_dyn, _1, _2);
  server.setCallback(f);

  cvNamedWindow("After Color Filtering", CV_WINDOW_NORMAL);
  cvNamedWindow("Contours", CV_WINDOW_NORMAL);
  cvNamedWindow("LINES", CV_WINDOW_NORMAL);

  if (flag)
  {
    cvNamedWindow("F1", CV_WINDOW_NORMAL);
    cvNamedWindow("F2", CV_WINDOW_NORMAL);
    cvNamedWindow("F3", CV_WINDOW_NORMAL);

    cvCreateTrackbar("t1min", "F1", &t1min, 260, NULL);
    cvCreateTrackbar("t1max", "F1", &t1max, 260, NULL);
    cvCreateTrackbar("t2min", "F2", &t2min, 260, NULL);
    cvCreateTrackbar("t2max", "F2", &t2max, 260, NULL);
    cvCreateTrackbar("t3min", "F3", &t3min, 260, NULL);
    cvCreateTrackbar("t3max", "F3", &t3max, 260, NULL);
  }
  // capture size -
  CvSize size = cvSize(width, height);

  // Initialize different images that are going to be used in the program
  cv::Mat hsv_frame, thresholded, thresholded1, thresholded2, thresholded3, filtered;  // image converted to HSV plane
  // asking for the minimum distance where bwe fire torpedo

  while (ros::ok())
  {
    loop_rate.sleep();
    // Get one frame
    if (frame.empty())
    {
      ROS_INFO("%s: empty frame", ros::this_node::getName().c_str());
      ros::spinOnce();
      continue;
    }

    if (video)
      output_cap.write(frame);

    // get the image data
    height = frame.rows;
    width = frame.cols;
    step = frame.step;

    // Covert color space to HSV as it is much easier to filter colors in the HSV color-space.
    cv::cvtColor(frame, hsv_frame, CV_BGR2HSV);

    cv::Scalar hsv_min = cv::Scalar(t1min, t2min, t3min, 0);
    cv::Scalar hsv_max = cv::Scalar(t1max, t2max, t3max, 0);

    // Filter out colors which are out of range.
    cv::inRange(hsv_frame, hsv_min, hsv_max, thresholded);
    // Split image into its 3 one dimensional images
    cv::Mat thresholded_hsv[3];
    cv::split(hsv_frame, thresholded_hsv);

    // Filter out colors which are out of range.
    cv::inRange(thresholded_hsv[0], cv::Scalar(t1min, 0, 0, 0), cv::Scalar(t1max, 0, 0, 0), thresholded_hsv[0]);
    cv::inRange(thresholded_hsv[1], cv::Scalar(t2min, 0, 0, 0), cv::Scalar(t2max, 0, 0, 0), thresholded_hsv[1]);
    cv::inRange(thresholded_hsv[2], cv::Scalar(t3min, 0, 0, 0), cv::Scalar(t3max, 0, 0, 0), thresholded_hsv[2]);

    cv::GaussianBlur(thresholded, thresholded, cv::Size(9, 9), 0, 0, 0);
    cv::imshow("After Color Filtering", thresholded);  // The stream after color filtering

    if (flag)
    {
      cv::imshow("F1", thresholded_hsv[0]);  // individual filters
      cv::imshow("F2", thresholded_hsv[1]);
      cv::imshow("F3", thresholded_hsv[2]);
    }

    if ((cvWaitKey(10) & 255) == 27)
      break;

    if (!IP)
    {
      // find contours
      std::vector<std::vector<cv::Point> > contours;
      cv::Mat thresholded_Mat = thresholded;
      findContours(thresholded_Mat, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);  // Find the contours in the image
      double largest_area = 0, largest_contour_index = 0;
      if (contours.empty())
      {
        msg.data = -finalAngle * (180 / 3.14) + 90;
        pub.publish(msg);
        ros::spinOnce();
        // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
        // remove higher bits using AND operator
        if ((cvWaitKey(10) & 255) == 27)
          break;
        continue;
      }

      for (int i = 0; i < contours.size(); i++)  // iterate through each contour.
      {
        double a = contourArea(contours[i], false);  //  Find the area of contour
        if (a > largest_area)
        {
          largest_area = a;
          largest_contour_index = i;  // Store the index of largest contour
        }
      }
      // Convex HULL
      std::vector<std::vector<cv::Point> > hull(contours.size());
      convexHull(cv::Mat(contours[largest_contour_index]), hull[largest_contour_index], false);

      cv::Mat Drawing(thresholded_Mat.rows, thresholded_Mat.cols, CV_8UC1, cv::Scalar::all(0));
      std::vector<cv::Vec4i> hierarchy;
      cv::Scalar color(255, 255, 255);
      drawContours(Drawing, contours, largest_contour_index, color, 2, 8, hierarchy);
      cv::imshow("Contours", Drawing);

      std_msgs::Float64 msg;
      Drawing.copyTo(sent_to_callback);
      /*
      msg.data never takes positive 90
      when the angle is 90 it will show -90
      -------------TO BE CORRECTED-------------
      */
      msg.data = -finalAngle * (180 / 3.14);
      if (lineCount > 0)
      {
        pub.publish(msg);
      }
      callback(0, 0);  // for displaying the thresholded image initially
      ros::spinOnce();
      // loop_rate.sleep();

      // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
      // remove higher bits using AND operator
      if ((cvWaitKey(10) & 255) == 27)
        break;
      if ((cvWaitKey(10) & 255) == 32)
      {
        if (m == 32)
          m = -1;
        else
          m = 32;
      }
      if (m == 32)
        ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
      ros::spinOnce();
    }
    else
    {
      ROS_INFO("%s: waiting\n", ros::this_node::getName().c_str());
      if ((cvWaitKey(10) & 255) == 32)
      {
        if (m == 32)
          x = -1;
        else
          m = 32;
      }
      if (m == 32)
        ROS_INFO("%s: PAUSED\n", ros::this_node::getName().c_str());
      ros::spinOnce();
    }
  }
  output_cap.release();
  return 0;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2007 by carm   *
 *   carm@localhost   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#ifndef QPROJECTM_MAINWINDOW_H
#define QPROJECTM_MAINWINDOW_H
#define CONFIG_FILE "/share/projectM/config.inp"

#include <QMainWindow>
#include <QCloseEvent>
#include <cassert>
#include <QGLWidget>
#include <QHash>
#include <QtDebug>
#include <QMutex>

#include "projectM.hpp"

class QHeaderView;
class QAction;
class QMenu;
class QPresetFileDialog;
class QPlaylistFileDialog;
class QPlaylistModel;
class QModelIndex;
class QProjectMConfigDialog;

namespace Ui {
class QProjectM_MainWindow;
}

#include <iostream>

class QProjectM : public QObject, public projectM {
	Q_OBJECT

	public:
		 QProjectM(const std::string & config_file):projectM(config_file) {}

		 void presetSwitchedEvent(bool hardCut, unsigned int index) const {
			presetSwitchedSignal(hardCut, index);
		 }
	signals:
		void presetSwitchedSignal(bool hardCut, unsigned int index) const;
	public slots:

};

class QProjectMWidget : public QGLWidget
 {
     Q_OBJECT        // must include this if you use Qt signals/slots

 public:
     QProjectMWidget(const std::string & _config_file, QWidget *parent, QMutex * audioMutex = 0)
         : QGLWidget(parent), config_file(_config_file), m_projectM(0), m_audioMutex(audioMutex) {}

     ~QProjectMWidget() { destroyProjectM(); }

     inline const std::string & configFile() {
	     return config_file;
     }

     QProjectM * getQProjectM() { return m_projectM; }

	 private:
     	     void destroyProjectM() {
	     emit(projectM_BeforeDestroy());

	     if (m_projectM) {
		     delete(m_projectM);
		     m_projectM = 0;
	     }
     }

 public slots:

     void resetProjectM() {

	qDebug() << "reset start";
	// First wait for audio thread to stop by
	// waiting on it's mutex
//	s_audioMutex.tryLock(20000);
	if (m_audioMutex) {
		qDebug() << "lock set start!";
		m_audioMutex->lock();
		qDebug() << "lock set end!";
	}
	// Now destroy the projectM instance
	destroyProjectM();

	// Make a new projectM instance and reset the opengl state
	initializeGL();

	// Allow audio thread to continue its business
	if (m_audioMutex) {
	//	m_audioMutex->unlock();
	//	qDebug() << "UNLOCKED";
	}
	qDebug() << "reinit'ed";
     }

     void setAudioMutex(QMutex * mutex) {
	     m_audioMutex = mutex;
     }

     void setPresetLock(int state) {
		m_projectM->setPresetLock((bool)state);
		emit(presetLockChanged((bool)state));
     }
  signals:
	void projectM_BeforeDestroy();
	void projectM_Initialized(QProjectM *);
	void presetLockChanged(bool isLocked);
 private:
	std::string config_file;
	QProjectM * m_projectM;

	QMutex * m_audioMutex;
 protected:

void keyReleaseEvent ( QKeyEvent * e )  {

    projectMKeycode pkey;
    bool ignore = false;
    switch (e->key()) {
	case Qt::Key_F4:
		pkey =  PROJECTM_K_F4;
		break;
	case Qt::Key_F3:
		pkey =  PROJECTM_K_F3;
		break;
	case Qt::Key_F2:
		pkey =  PROJECTM_K_F2;
		break;
	case Qt::Key_F1:
		pkey =  PROJECTM_K_F1;
		break;
	case Qt::Key_R:
		pkey =  PROJECTM_K_r;
		break;
	case Qt::Key_L:
		pkey =  PROJECTM_K_l;
		ignore = true;
		break;
	case Qt::Key_N:
  		pkey =  PROJECTM_K_n;
		break;
	case Qt::Key_P:
		pkey =  PROJECTM_K_p;
		break;
	default:
		e->ignore();
		return;
    }
       projectMModifier modifier;

	m_projectM->key_handler(PROJECTM_KEYDOWN, pkey, modifier);
	if (ignore)
		e->ignore();

     }

     void initializeGL()
     {

	this->m_projectM = new QProjectM(config_file);
	projectM_Initialized(m_projectM);
     }

     void resizeGL(int w, int h)
     {
        // Setup viewport, projection etc
	setup_opengl(w,h);
	m_projectM->projectM_resetGL(  w, h );
     }

     void paintGL()
     {
   	m_projectM->renderFrame();
     }

   private:

 void setup_opengl( int w, int h )
{

    /* Our shading model--Gouraud (smooth). */
     glShadeModel( GL_SMOOTH);
    /* Culling. */
    //    glCullFace( GL_BACK );
    //    glFrontFace( GL_CCW );
    //    glEnable( GL_CULL_FACE );
    /* Set the clear color. */
    glClearColor( 0, 0, 0, 0 );
    /* Setup our viewport. */
     glViewport( 0, 0, w, h );
    /*
     * Change to the projection matrix and set
     * our viewing volume.
     */
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();

    //    gluOrtho2D(0.0, (GLfloat) width, 0.0, (GLfloat) height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

  //    glFrustum(0.0, height, 0.0,width,10,40);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glDrawBuffer(GL_BACK);
  glReadBuffer(GL_BACK);
  glEnable(GL_BLEND);

     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
     // glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  glEnable(GL_LINE_SMOOTH);
  glEnable(GL_POINT_SMOOTH);
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
//   glClear(GL_COLOR_BUFFER_BIT);

  // glCopyTexImage2D(GL_TEXTURE_2D,0,GL_RGB,0,0,texsize,texsize,0);
  //glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,texsize,texsize);
   glLineStipple(2, 0xAAAA);

}

 };

class QProjectM_MainWindow:public QMainWindow
{
      Q_OBJECT

public:
      typedef struct PlaylistItemMetaData {
		PlaylistItemMetaData() {}
		PlaylistItemMetaData(const QString & _url, const QString & _name, int _rating):
			url(_url), name(_name), rating(_rating) {}

		QString url;
		QString name;
		int rating;
      } PlaylistItemMetaData;

      typedef QVector<PlaylistItemMetaData> PlaylistItemVector;

      QProjectM_MainWindow(const std::string & config_file, QMutex * audioMutex);
      virtual ~QProjectM_MainWindow();
      void registerSettingsAction(QAction * action);
      void unregisterSettingsAction(QAction * action);
      void setMenuVisible(bool visible);

      void keyReleaseEvent ( QKeyEvent * e );
      QProjectM * getQProjectM();
      void refreshPlaylist();

      QProjectMWidget * getQProjectMWidget() { return m_QProjectMWidget; }

      void registerAction(const QAction &);

protected:

            void closeEvent(QCloseEvent *event);

private slots:

      void aboutQt();
      void clearPlaylist();
      void addPresets();
      void openPlaylist();
      void savePlaylist();
      void about();
      void postProjectM_Initialize();
      void updatePlaylistSelection(bool hardCut, unsigned int index);
      void selectPlaylistItem(const QModelIndex & index);
      void changeRating(const QModelIndex & index);
      void openSettingsDialog();
      void updateFilteredPlaylist(const QString & text);
      void refreshHeaders(QResizeEvent * event = 0);

	private:
		QSize _oldPlaylistSize;

	void readConfig(const std::string & configFile);
	void writeConfig();
	void copyPlaylist();

	QHeaderView * hHeader;
	QHeaderView * vHeader;
      QString m_currentPlaylistFile;

      QPlaylistModel * playlistModel;
      Ui::QProjectM_MainWindow * ui;
      QProjectMConfigDialog * configDialog;

      QHash<QString, PlaylistItemVector*> historyHash;

      bool _menuVisible;
      int oldPresetIndex;
      QTimer * m_timer;

      void createActions();
      void createMenus();
      void createToolBars();
      void createStatusBar();
      void readSettings();
      void writeSettings();
      void loadFile(const QString &fileName, int rating = 3);
      QString strippedName(const QString &fullFileName);

      QProjectMWidget * m_QProjectMWidget;

      QMenu *fileMenu;
      QMenu *helpMenu;
      QToolBar *fileToolBar;

      QAction *openAct;;
      QAction *exitAct;
      QAction *aboutAct;
      QAction *aboutQtAct;

      QString previousFilter;

      QPresetFileDialog * m_QPresetFileDialog;
      QPlaylistFileDialog * m_QPlaylistFileDialog;

};

#endif
<commit_msg>mouse click on projectM widget now steals focus<commit_after>/***************************************************************************
 *   Copyright (C) 2007 by carm   *
 *   carm@localhost   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#ifndef QPROJECTM_MAINWINDOW_H
#define QPROJECTM_MAINWINDOW_H
#define CONFIG_FILE "/share/projectM/config.inp"

#include <QMainWindow>
#include <QCloseEvent>
#include <cassert>
#include <QGLWidget>
#include <QHash>
#include <QtDebug>
#include <QMutex>

#include "projectM.hpp"

class QHeaderView;
class QAction;
class QMenu;
class QPresetFileDialog;
class QPlaylistFileDialog;
class QPlaylistModel;
class QModelIndex;
class QProjectMConfigDialog;

namespace Ui {
class QProjectM_MainWindow;
}

#include <iostream>

class QProjectM : public QObject, public projectM {
	Q_OBJECT

	public:
		 QProjectM(const std::string & config_file):projectM(config_file) {}

		 void presetSwitchedEvent(bool hardCut, unsigned int index) const {
			presetSwitchedSignal(hardCut, index);
		 }
	signals:
		void presetSwitchedSignal(bool hardCut, unsigned int index) const;
	public slots:

};

class QProjectMWidget : public QGLWidget
 {
     Q_OBJECT        // must include this if you use Qt signals/slots

 public:
     QProjectMWidget(const std::string & _config_file, QWidget *parent, QMutex * audioMutex = 0)
         : QGLWidget(parent), config_file(_config_file), m_projectM(0), m_audioMutex(audioMutex) {}

     ~QProjectMWidget() { destroyProjectM(); }

     inline const std::string & configFile() {
	     return config_file;
     }

     QProjectM * getQProjectM() { return m_projectM; }

	 private:
     	     void destroyProjectM() {
	     emit(projectM_BeforeDestroy());

	     if (m_projectM) {
		     delete(m_projectM);
		     m_projectM = 0;
	     }
     }

 public slots:

     void resetProjectM() {

	qDebug() << "reset start";
	// First wait for audio thread to stop by
	// waiting on it's mutex
//	s_audioMutex.tryLock(20000);
	if (m_audioMutex) {
		qDebug() << "lock set start!";
		m_audioMutex->lock();
		qDebug() << "lock set end!";
	}
	// Now destroy the projectM instance
	destroyProjectM();

	// Make a new projectM instance and reset the opengl state
	initializeGL();

	// Allow audio thread to continue its business
	if (m_audioMutex) {
	//	m_audioMutex->unlock();
	//	qDebug() << "UNLOCKED";
	}
	qDebug() << "reinit'ed";
     }

     void setAudioMutex(QMutex * mutex) {
	     m_audioMutex = mutex;
     }

     void setPresetLock(int state) {
		m_projectM->setPresetLock((bool)state);
		emit(presetLockChanged((bool)state));
     }

     void mousePressEvent ( QMouseEvent * event )   {
	     this->setFocus();
     }
  signals:
	void projectM_BeforeDestroy();
	void projectM_Initialized(QProjectM *);
	void presetLockChanged(bool isLocked);
 private:
	std::string config_file;
	QProjectM * m_projectM;

	QMutex * m_audioMutex;
 protected:

void keyReleaseEvent ( QKeyEvent * e )  {

    projectMKeycode pkey;
    bool ignore = false;
    switch (e->key()) {
	case Qt::Key_F4:
		pkey =  PROJECTM_K_F4;
		break;
	case Qt::Key_F3:
		pkey =  PROJECTM_K_F3;
		break;
	case Qt::Key_F2:
		pkey =  PROJECTM_K_F2;
		break;
	case Qt::Key_F1:
		pkey =  PROJECTM_K_F1;
		break;
	case Qt::Key_R:
		pkey =  PROJECTM_K_r;
		break;
	case Qt::Key_L:
		pkey =  PROJECTM_K_l;
		ignore = true;
		break;
	case Qt::Key_N:
  		pkey =  PROJECTM_K_n;
		break;
	case Qt::Key_P:
		pkey =  PROJECTM_K_p;
		break;
	default:
		e->ignore();
		return;
    }
       projectMModifier modifier;

	m_projectM->key_handler(PROJECTM_KEYDOWN, pkey, modifier);
	if (ignore)
		e->ignore();

     }

     void initializeGL()
     {

	this->m_projectM = new QProjectM(config_file);
	projectM_Initialized(m_projectM);
     }

     void resizeGL(int w, int h)
     {
        // Setup viewport, projection etc
	setup_opengl(w,h);
	m_projectM->projectM_resetGL(  w, h );
     }

     void paintGL()
     {
   	m_projectM->renderFrame();
     }

   private:

 void setup_opengl( int w, int h )
{

    /* Our shading model--Gouraud (smooth). */
     glShadeModel( GL_SMOOTH);
    /* Culling. */
    //    glCullFace( GL_BACK );
    //    glFrontFace( GL_CCW );
    //    glEnable( GL_CULL_FACE );
    /* Set the clear color. */
    glClearColor( 0, 0, 0, 0 );
    /* Setup our viewport. */
     glViewport( 0, 0, w, h );
    /*
     * Change to the projection matrix and set
     * our viewing volume.
     */
    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();

    //    gluOrtho2D(0.0, (GLfloat) width, 0.0, (GLfloat) height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

  //    glFrustum(0.0, height, 0.0,width,10,40);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glDrawBuffer(GL_BACK);
  glReadBuffer(GL_BACK);
  glEnable(GL_BLEND);

     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
     // glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  glEnable(GL_LINE_SMOOTH);
  glEnable(GL_POINT_SMOOTH);
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
//   glClear(GL_COLOR_BUFFER_BIT);

  // glCopyTexImage2D(GL_TEXTURE_2D,0,GL_RGB,0,0,texsize,texsize,0);
  //glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,texsize,texsize);
   glLineStipple(2, 0xAAAA);

}

 };

class QProjectM_MainWindow:public QMainWindow
{
      Q_OBJECT

public:
      typedef struct PlaylistItemMetaData {
		PlaylistItemMetaData() {}
		PlaylistItemMetaData(const QString & _url, const QString & _name, int _rating):
			url(_url), name(_name), rating(_rating) {}

		QString url;
		QString name;
		int rating;
      } PlaylistItemMetaData;

      typedef QVector<PlaylistItemMetaData> PlaylistItemVector;

      QProjectM_MainWindow(const std::string & config_file, QMutex * audioMutex);
      virtual ~QProjectM_MainWindow();
      void registerSettingsAction(QAction * action);
      void unregisterSettingsAction(QAction * action);
      void setMenuVisible(bool visible);

      void keyReleaseEvent ( QKeyEvent * e );
      QProjectM * getQProjectM();
      void refreshPlaylist();

      QProjectMWidget * getQProjectMWidget() { return m_QProjectMWidget; }

      void registerAction(const QAction &);

protected:

            void closeEvent(QCloseEvent *event);

private slots:

      void aboutQt();
      void clearPlaylist();
      void addPresets();
      void openPlaylist();
      void savePlaylist();
      void about();
      void postProjectM_Initialize();
      void updatePlaylistSelection(bool hardCut, unsigned int index);
      void selectPlaylistItem(const QModelIndex & index);
      void changeRating(const QModelIndex & index);
      void openSettingsDialog();
      void updateFilteredPlaylist(const QString & text);
      void refreshHeaders(QResizeEvent * event = 0);

	private:
		QSize _oldPlaylistSize;

	void readConfig(const std::string & configFile);
	void writeConfig();
	void copyPlaylist();

	QHeaderView * hHeader;
	QHeaderView * vHeader;
      QString m_currentPlaylistFile;

      QPlaylistModel * playlistModel;
      Ui::QProjectM_MainWindow * ui;
      QProjectMConfigDialog * configDialog;

      QHash<QString, PlaylistItemVector*> historyHash;

      bool _menuVisible;
      int oldPresetIndex;
      QTimer * m_timer;

      void createActions();
      void createMenus();
      void createToolBars();
      void createStatusBar();
      void readSettings();
      void writeSettings();
      void loadFile(const QString &fileName, int rating = 3);
      QString strippedName(const QString &fullFileName);

      QProjectMWidget * m_QProjectMWidget;

      QMenu *fileMenu;
      QMenu *helpMenu;
      QToolBar *fileToolBar;

      QAction *openAct;;
      QAction *exitAct;
      QAction *aboutAct;
      QAction *aboutQtAct;

      QString previousFilter;

      QPresetFileDialog * m_QPresetFileDialog;
      QPlaylistFileDialog * m_QPlaylistFileDialog;

};

#endif
<|endoftext|>


<commit_before>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include "com/centreon/broker/compression/opener.hh"
#include "com/centreon/broker/compression/stream.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::compression;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
opener::opener() : io::endpoint(false), _level(-1), _size(0) {}

/**
 *  Copy constructor.
 *
 *  @param[in] o Object to copy.
 */
opener::opener(opener const& o)
  : io::endpoint(o),
    _level(o._level),
    _size(o._size) {}

/**
 *  Destructor.
 */
opener::~opener() {}

/**
 *  Assignment operator.
 *
 *  @param[in] o Object to copy.
 *
 *  @return This object.
 */
opener& opener::operator=(opener const& o) {
  if (this != &o) {
    io::endpoint::operator=(o);
    _level = o._level;
    _size = o._size;
  }
  return (*this);
}

/**
 *  Close the opener.
 */
void opener::close() {
  return ;
}

/**
 *  Open a compression stream.
 *
 *  @return New compression object.
 */
misc::shared_ptr<io::stream> opener::open() {
  misc::shared_ptr<io::stream> retval;
  if (!_from.isNull()) {
    misc::shared_ptr<io::stream> base(_from->open());
    if (!base.isNull()) {
      retval = misc::shared_ptr<io::stream>(new stream(_level, _size));
      retval->read_from(base);
      retval->write_to(base);
    }
  }
  return (retval);
}

/**
 *  Set the compression level.
 *
 *  @param[in] level Compression level (between 1 and 9, default is -1).
 */
void opener::set_level(int level) {
  _level = level;
  return ;
}

/**
 *  Set the compression buffer size.
 *
 *  @param[in] size Compression buffer size (default is 0 which means no
 *                  buffering).
 */
void opener::set_size(unsigned int size) {
  _size = size;
  return ;
}
<commit_msg>The compression opener was not properly forwarding the close signal. This fixes #3501.<commit_after>/*
** Copyright 2011-2012 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include "com/centreon/broker/compression/opener.hh"
#include "com/centreon/broker/compression/stream.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::compression;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Default constructor.
 */
opener::opener() : io::endpoint(false), _level(-1), _size(0) {}

/**
 *  Copy constructor.
 *
 *  @param[in] o Object to copy.
 */
opener::opener(opener const& o)
  : io::endpoint(o),
    _level(o._level),
    _size(o._size) {}

/**
 *  Destructor.
 */
opener::~opener() {}

/**
 *  Assignment operator.
 *
 *  @param[in] o Object to copy.
 *
 *  @return This object.
 */
opener& opener::operator=(opener const& o) {
  if (this != &o) {
    io::endpoint::operator=(o);
    _level = o._level;
    _size = o._size;
  }
  return (*this);
}

/**
 *  Close the opener.
 */
void opener::close() {
  if (!_from.isNull())
    _from->close();
  return ;
}

/**
 *  Open a compression stream.
 *
 *  @return New compression object.
 */
misc::shared_ptr<io::stream> opener::open() {
  misc::shared_ptr<io::stream> retval;
  if (!_from.isNull()) {
    misc::shared_ptr<io::stream> base(_from->open());
    if (!base.isNull()) {
      retval = misc::shared_ptr<io::stream>(new stream(_level, _size));
      retval->read_from(base);
      retval->write_to(base);
    }
  }
  return (retval);
}

/**
 *  Set the compression level.
 *
 *  @param[in] level Compression level (between 1 and 9, default is -1).
 */
void opener::set_level(int level) {
  _level = level;
  return ;
}

/**
 *  Set the compression buffer size.
 *
 *  @param[in] size Compression buffer size (default is 0 which means no
 *                  buffering).
 */
void opener::set_size(unsigned int size) {
  _size = size;
  return ;
}
<|endoftext|>