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

#include "chrome/browser/history/history_publisher.h"

#include <atlsafe.h>
#include <objbase.h>
#include <oleauto.h>
#include <wtypes.h>

#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"

namespace {

// Instantiates a IChromeHistoryIndexer COM object. Takes a COM class id
// in |name| and returns the object in |indexer|. Returns false if the
// operation fails.
bool CoCreateIndexerFromName(const wchar_t* name,
                             IChromeHistoryIndexer** indexer) {
  CLSID clsid;
  HRESULT hr = CLSIDFromString(const_cast<wchar_t*>(name), &clsid);
  if (FAILED(hr))
    return false;
  hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC,
                        __uuidof(IChromeHistoryIndexer),
                        reinterpret_cast<void**>(indexer));
  if (FAILED(hr))
    return false;
  return true;
}

// Instantiates the registered indexers from the registry |root| + |path| key
// and adds them to the |indexers| list.
void AddRegisteredIndexers(HKEY root, const wchar_t* path,
    std::vector< ScopedComPtr<IChromeHistoryIndexer> >* indexers) {
  IChromeHistoryIndexer* indexer;
  RegistryKeyIterator r_iter(root, path);
  while (r_iter.Valid()) {
    if (CoCreateIndexerFromName(r_iter.Name(), &indexer)) {
      indexers->push_back(ScopedComPtr<IChromeHistoryIndexer>(indexer));
      indexer->Release();
    }
    ++r_iter;
  }
}

}  // namespace

namespace history {

const wchar_t* const HistoryPublisher::kRegKeyRegisteredIndexersInfo =
    L"Software\\Google\\Google Chrome\\IndexerPlugins";

// static
double HistoryPublisher::TimeToUTCVariantTime(const base::Time& time) {
  double var_time = 0;
  if (!time.is_null()) {
    base::Time::Exploded exploded;
    time.UTCExplode(&exploded);

    // Create the system time struct representing our exploded time.
    SYSTEMTIME system_time;
    system_time.wYear = exploded.year;
    system_time.wMonth = exploded.month;
    system_time.wDayOfWeek = exploded.day_of_week;
    system_time.wDay = exploded.day_of_month;
    system_time.wHour = exploded.hour;
    system_time.wMinute = exploded.minute;
    system_time.wSecond = exploded.second;
    system_time.wMilliseconds = exploded.millisecond;
    SystemTimeToVariantTime(&system_time, &var_time);
  }

  return var_time;
}

HistoryPublisher::HistoryPublisher() {
  CoInitialize(NULL);
}

HistoryPublisher::~HistoryPublisher() {
  CoUninitialize();
}

bool HistoryPublisher::Init() {
  return ReadRegisteredIndexersFromRegistry();
}

// Peruse the registry for Indexer to instantiate and store in |indexers_|.
// Return true if we found at least one indexer object. We look both in HKCU
// and HKLM.
bool HistoryPublisher::ReadRegisteredIndexersFromRegistry() {
  AddRegisteredIndexers(HKEY_CURRENT_USER,
                        kRegKeyRegisteredIndexersInfo, &indexers_);
  AddRegisteredIndexers(HKEY_LOCAL_MACHINE,
                        kRegKeyRegisteredIndexersInfo, &indexers_);
  return indexers_.size() > 0;
}

void HistoryPublisher::PublishDataToIndexers(const PageData& page_data)
    const {
  double var_time = TimeToUTCVariantTime(page_data.time);

  CComSafeArray<unsigned char> thumbnail_arr;
  if (page_data.thumbnail) {
    for (size_t i = 0; i < page_data.thumbnail->size(); ++i)
      thumbnail_arr.Add((*page_data.thumbnail)[i]);
  }

  // Send data to registered indexers.
  ScopedVariant time(var_time, VT_DATE);
  ScopedBstr url(ASCIIToWide(page_data.url.spec()).c_str());
  ScopedBstr html(page_data.html);
  ScopedBstr title(page_data.title);
  ScopedBstr format(ASCIIToWide(page_data.thumbnail_format).c_str());
  ScopedVariant psa(thumbnail_arr.m_psa);
  for (size_t i = 0; i < indexers_.size(); ++i) {
    indexers_[i]->SendPageData(time, url, html, title, format, psa);
  }
}

void HistoryPublisher::DeleteUserHistoryBetween(const base::Time& begin_time,
                                                const base::Time& end_time)
    const {
  ScopedVariant var_begin_time(TimeToUTCVariantTime(begin_time), VT_DATE);
  ScopedVariant var_end_time(TimeToUTCVariantTime(end_time), VT_DATE);
  for (size_t i = 0; i < indexers_.size(); ++i) {
    indexers_[i]->DeleteUserHistoryBetween(var_begin_time, var_end_time);
  }
}

}  // namespace history
<commit_msg>Fix a crash in the history publisher. This is caused by me changing the signature of ASCIIToWide to no longer take a string piece. This changed the behavior for NULL handling (NULL is no longer supported).<commit_after>// Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/history/history_publisher.h"

#include <atlsafe.h>
#include <objbase.h>
#include <oleauto.h>
#include <wtypes.h>

#include "base/registry.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"

namespace {

// Instantiates a IChromeHistoryIndexer COM object. Takes a COM class id
// in |name| and returns the object in |indexer|. Returns false if the
// operation fails.
bool CoCreateIndexerFromName(const wchar_t* name,
                             IChromeHistoryIndexer** indexer) {
  CLSID clsid;
  HRESULT hr = CLSIDFromString(const_cast<wchar_t*>(name), &clsid);
  if (FAILED(hr))
    return false;
  hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC,
                        __uuidof(IChromeHistoryIndexer),
                        reinterpret_cast<void**>(indexer));
  if (FAILED(hr))
    return false;
  return true;
}

// Instantiates the registered indexers from the registry |root| + |path| key
// and adds them to the |indexers| list.
void AddRegisteredIndexers(HKEY root, const wchar_t* path,
    std::vector< ScopedComPtr<IChromeHistoryIndexer> >* indexers) {
  IChromeHistoryIndexer* indexer;
  RegistryKeyIterator r_iter(root, path);
  while (r_iter.Valid()) {
    if (CoCreateIndexerFromName(r_iter.Name(), &indexer)) {
      indexers->push_back(ScopedComPtr<IChromeHistoryIndexer>(indexer));
      indexer->Release();
    }
    ++r_iter;
  }
}

}  // namespace

namespace history {

const wchar_t* const HistoryPublisher::kRegKeyRegisteredIndexersInfo =
    L"Software\\Google\\Google Chrome\\IndexerPlugins";

// static
double HistoryPublisher::TimeToUTCVariantTime(const base::Time& time) {
  double var_time = 0;
  if (!time.is_null()) {
    base::Time::Exploded exploded;
    time.UTCExplode(&exploded);

    // Create the system time struct representing our exploded time.
    SYSTEMTIME system_time;
    system_time.wYear = exploded.year;
    system_time.wMonth = exploded.month;
    system_time.wDayOfWeek = exploded.day_of_week;
    system_time.wDay = exploded.day_of_month;
    system_time.wHour = exploded.hour;
    system_time.wMinute = exploded.minute;
    system_time.wSecond = exploded.second;
    system_time.wMilliseconds = exploded.millisecond;
    SystemTimeToVariantTime(&system_time, &var_time);
  }

  return var_time;
}

HistoryPublisher::HistoryPublisher() {
  CoInitialize(NULL);
}

HistoryPublisher::~HistoryPublisher() {
  CoUninitialize();
}

bool HistoryPublisher::Init() {
  return ReadRegisteredIndexersFromRegistry();
}

// Peruse the registry for Indexer to instantiate and store in |indexers_|.
// Return true if we found at least one indexer object. We look both in HKCU
// and HKLM.
bool HistoryPublisher::ReadRegisteredIndexersFromRegistry() {
  AddRegisteredIndexers(HKEY_CURRENT_USER,
                        kRegKeyRegisteredIndexersInfo, &indexers_);
  AddRegisteredIndexers(HKEY_LOCAL_MACHINE,
                        kRegKeyRegisteredIndexersInfo, &indexers_);
  return indexers_.size() > 0;
}

void HistoryPublisher::PublishDataToIndexers(const PageData& page_data)
    const {
  double var_time = TimeToUTCVariantTime(page_data.time);

  CComSafeArray<unsigned char> thumbnail_arr;
  if (page_data.thumbnail) {
    for (size_t i = 0; i < page_data.thumbnail->size(); ++i)
      thumbnail_arr.Add((*page_data.thumbnail)[i]);
  }

  // Send data to registered indexers.
  ScopedVariant time(var_time, VT_DATE);
  ScopedBstr url(ASCIIToWide(page_data.url.spec()).c_str());
  ScopedBstr html(page_data.html);
  ScopedBstr title(page_data.title);
  // Don't send a NULL string through ASCIIToWide.
  ScopedBstr format(page_data.thumbnail_format ?
      ASCIIToWide(page_data.thumbnail_format).c_str() :
      NULL);
  ScopedVariant psa(thumbnail_arr.m_psa);
  for (size_t i = 0; i < indexers_.size(); ++i) {
    indexers_[i]->SendPageData(time, url, html, title, format, psa);
  }
}

void HistoryPublisher::DeleteUserHistoryBetween(const base::Time& begin_time,
                                                const base::Time& end_time)
    const {
  ScopedVariant var_begin_time(TimeToUTCVariantTime(begin_time), VT_DATE);
  ScopedVariant var_end_time(TimeToUTCVariantTime(end_time), VT_DATE);
  for (size_t i = 0; i < indexers_.size(); ++i) {
    indexers_[i]->DeleteUserHistoryBetween(var_begin_time, var_end_time);
  }
}

}  // namespace history
<|endoftext|>


<commit_before>//===----------- ValueTypes.cpp - Implementation of MVT methods -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements methods in the CodeGen/ValueTypes.h header.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Type.h"
#include "llvm/DerivedTypes.h"
using namespace llvm;

MVT MVT::getExtendedIntegerVT(unsigned BitWidth) {
  MVT VT;
  VT.LLVMTy = IntegerType::get(BitWidth);
  assert(VT.isExtended() && "Type is not extended!");
  return VT;
}

MVT MVT::getExtendedVectorVT(MVT VT, unsigned NumElements) {
  MVT ResultVT;
  ResultVT.LLVMTy = VectorType::get(VT.getTypeForMVT(), NumElements);
  assert(ResultVT.isExtended() && "Type is not extended!");
  return ResultVT;
}

bool MVT::isExtendedFloatingPoint() const {
  assert(isExtended() && "Type is not extended!");
  return LLVMTy->isFPOrFPVector();
}

bool MVT::isExtendedInteger() const {
  assert(isExtended() && "Type is not extended!");
  return LLVMTy->isIntOrIntVector();
}

bool MVT::isExtendedVector() const {
  assert(isExtended() && "Type is not extended!");
  return isa<VectorType>(LLVMTy);
}

bool MVT::isExtended64BitVector() const {
  return isExtendedVector() && getSizeInBits() == 64;
}

bool MVT::isExtended128BitVector() const {
  return isExtendedVector() && getSizeInBits() == 128;
}

MVT MVT::getExtendedVectorElementType() const {
  assert(isExtended() && "Type is not extended!");
  return MVT::getMVT(cast<VectorType>(LLVMTy)->getElementType());
}

unsigned MVT::getExtendedVectorNumElements() const {
  assert(isExtended() && "Type is not extended!");
  return cast<VectorType>(LLVMTy)->getNumElements();
}

unsigned MVT::getExtendedSizeInBits() const {
  assert(isExtended() && "Type is not extended!");
  if (const IntegerType *ITy = dyn_cast<IntegerType>(LLVMTy))
    return ITy->getBitWidth();
  if (const VectorType *VTy = dyn_cast<VectorType>(LLVMTy))
    return VTy->getBitWidth();
  assert(false && "Unrecognized extended type!");
  return 0; // Suppress warnings.
}

/// getMVTString - This function returns value type as a string, e.g. "i32".
std::string MVT::getMVTString() const {
  switch (V) {
  default:
    if (isVector())
      return "v" + utostr(getVectorNumElements()) +
             getVectorElementType().getMVTString();
    if (isInteger())
      return "i" + utostr(getSizeInBits());
    assert(0 && "Invalid MVT!");
    return "?";
  case MVT::i1:      return "i1";
  case MVT::i8:      return "i8";
  case MVT::i16:     return "i16";
  case MVT::i32:     return "i32";
  case MVT::i64:     return "i64";
  case MVT::i128:    return "i128";
  case MVT::f32:     return "f32";
  case MVT::f64:     return "f64";
  case MVT::f80:     return "f80";
  case MVT::f128:    return "f128";
  case MVT::ppcf128: return "ppcf128";
  case MVT::isVoid:  return "isVoid";
  case MVT::Other:   return "ch";
  case MVT::Flag:    return "flag";
  case MVT::v8i8:    return "v8i8";
  case MVT::v4i16:   return "v4i16";
  case MVT::v2i32:   return "v2i32";
  case MVT::v1i64:   return "v1i64";
  case MVT::v16i8:   return "v16i8";
  case MVT::v8i16:   return "v8i16";
  case MVT::v4i32:   return "v4i32";
  case MVT::v2i64:   return "v2i64";
  case MVT::v2f32:   return "v2f32";
  case MVT::v4f32:   return "v4f32";
  case MVT::v2f64:   return "v2f64";
  case MVT::v3i32:   return "v3i32";
  case MVT::v3f32:   return "v3f32";
  }
}

/// getTypeForMVT - This method returns an LLVM type corresponding to the
/// specified MVT.  For integer types, this returns an unsigned type.  Note
/// that this will abort for types that cannot be represented.
const Type *MVT::getTypeForMVT() const {
  switch (V) {
  default:
    if (isVector())
      return VectorType::get(getVectorElementType().getTypeForMVT(),
                             getVectorNumElements());
    if (isInteger())
      return IntegerType::get(getSizeInBits());
    assert(0 && "MVT does not correspond to LLVM type!");
    return Type::VoidTy;
  case MVT::isVoid:  return Type::VoidTy;
  case MVT::i1:      return Type::Int1Ty;
  case MVT::i8:      return Type::Int8Ty;
  case MVT::i16:     return Type::Int16Ty;
  case MVT::i32:     return Type::Int32Ty;
  case MVT::i64:     return Type::Int64Ty;
  case MVT::i128:    return IntegerType::get(128);
  case MVT::f32:     return Type::FloatTy;
  case MVT::f64:     return Type::DoubleTy;
  case MVT::f80:     return Type::X86_FP80Ty;
  case MVT::f128:    return Type::FP128Ty;
  case MVT::ppcf128: return Type::PPC_FP128Ty;
  case MVT::v8i8:    return VectorType::get(Type::Int8Ty, 8);
  case MVT::v4i16:   return VectorType::get(Type::Int16Ty, 4);
  case MVT::v2i32:   return VectorType::get(Type::Int32Ty, 2);
  case MVT::v1i64:   return VectorType::get(Type::Int64Ty, 1);
  case MVT::v16i8:   return VectorType::get(Type::Int8Ty, 16);
  case MVT::v8i16:   return VectorType::get(Type::Int16Ty, 8);
  case MVT::v4i32:   return VectorType::get(Type::Int32Ty, 4);
  case MVT::v2i64:   return VectorType::get(Type::Int64Ty, 2);
  case MVT::v2f32:   return VectorType::get(Type::FloatTy, 2);
  case MVT::v4f32:   return VectorType::get(Type::FloatTy, 4);
  case MVT::v2f64:   return VectorType::get(Type::DoubleTy, 2);
  case MVT::v3i32:   return VectorType::get(Type::Int32Ty, 3);
  case MVT::v3f32:   return VectorType::get(Type::FloatTy, 3);
  }
}

/// getMVT - Return the value type corresponding to the specified type.  This
/// returns all pointers as MVT::iPTR.  If HandleUnknown is true, unknown types
/// are returned as Other, otherwise they are invalid.
MVT MVT::getMVT(const Type *Ty, bool HandleUnknown){
  switch (Ty->getTypeID()) {
  default:
    if (HandleUnknown) return MVT::Other;
    assert(0 && "Unknown type!");
    return MVT::isVoid;
  case Type::VoidTyID:
    return MVT::isVoid;
  case Type::IntegerTyID:
    return getIntegerVT(cast<IntegerType>(Ty)->getBitWidth());
  case Type::FloatTyID:     return MVT::f32;
  case Type::DoubleTyID:    return MVT::f64;
  case Type::X86_FP80TyID:  return MVT::f80;
  case Type::FP128TyID:     return MVT::f128;
  case Type::PPC_FP128TyID: return MVT::ppcf128;
  case Type::PointerTyID:   return MVT::iPTR;
  case Type::VectorTyID: {
    const VectorType *VTy = cast<VectorType>(Ty);
    return getVectorVT(getMVT(VTy->getElementType(), false),
                       VTy->getNumElements());
  }
  }
}
<commit_msg>Duncan pointed out that the Extended case in getTypeForMVT could be considerably simplified.<commit_after>//===----------- ValueTypes.cpp - Implementation of MVT methods -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements methods in the CodeGen/ValueTypes.h header.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Type.h"
#include "llvm/DerivedTypes.h"
using namespace llvm;

MVT MVT::getExtendedIntegerVT(unsigned BitWidth) {
  MVT VT;
  VT.LLVMTy = IntegerType::get(BitWidth);
  assert(VT.isExtended() && "Type is not extended!");
  return VT;
}

MVT MVT::getExtendedVectorVT(MVT VT, unsigned NumElements) {
  MVT ResultVT;
  ResultVT.LLVMTy = VectorType::get(VT.getTypeForMVT(), NumElements);
  assert(ResultVT.isExtended() && "Type is not extended!");
  return ResultVT;
}

bool MVT::isExtendedFloatingPoint() const {
  assert(isExtended() && "Type is not extended!");
  return LLVMTy->isFPOrFPVector();
}

bool MVT::isExtendedInteger() const {
  assert(isExtended() && "Type is not extended!");
  return LLVMTy->isIntOrIntVector();
}

bool MVT::isExtendedVector() const {
  assert(isExtended() && "Type is not extended!");
  return isa<VectorType>(LLVMTy);
}

bool MVT::isExtended64BitVector() const {
  return isExtendedVector() && getSizeInBits() == 64;
}

bool MVT::isExtended128BitVector() const {
  return isExtendedVector() && getSizeInBits() == 128;
}

MVT MVT::getExtendedVectorElementType() const {
  assert(isExtended() && "Type is not extended!");
  return MVT::getMVT(cast<VectorType>(LLVMTy)->getElementType());
}

unsigned MVT::getExtendedVectorNumElements() const {
  assert(isExtended() && "Type is not extended!");
  return cast<VectorType>(LLVMTy)->getNumElements();
}

unsigned MVT::getExtendedSizeInBits() const {
  assert(isExtended() && "Type is not extended!");
  if (const IntegerType *ITy = dyn_cast<IntegerType>(LLVMTy))
    return ITy->getBitWidth();
  if (const VectorType *VTy = dyn_cast<VectorType>(LLVMTy))
    return VTy->getBitWidth();
  assert(false && "Unrecognized extended type!");
  return 0; // Suppress warnings.
}

/// getMVTString - This function returns value type as a string, e.g. "i32".
std::string MVT::getMVTString() const {
  switch (V) {
  default:
    if (isVector())
      return "v" + utostr(getVectorNumElements()) +
             getVectorElementType().getMVTString();
    if (isInteger())
      return "i" + utostr(getSizeInBits());
    assert(0 && "Invalid MVT!");
    return "?";
  case MVT::i1:      return "i1";
  case MVT::i8:      return "i8";
  case MVT::i16:     return "i16";
  case MVT::i32:     return "i32";
  case MVT::i64:     return "i64";
  case MVT::i128:    return "i128";
  case MVT::f32:     return "f32";
  case MVT::f64:     return "f64";
  case MVT::f80:     return "f80";
  case MVT::f128:    return "f128";
  case MVT::ppcf128: return "ppcf128";
  case MVT::isVoid:  return "isVoid";
  case MVT::Other:   return "ch";
  case MVT::Flag:    return "flag";
  case MVT::v8i8:    return "v8i8";
  case MVT::v4i16:   return "v4i16";
  case MVT::v2i32:   return "v2i32";
  case MVT::v1i64:   return "v1i64";
  case MVT::v16i8:   return "v16i8";
  case MVT::v8i16:   return "v8i16";
  case MVT::v4i32:   return "v4i32";
  case MVT::v2i64:   return "v2i64";
  case MVT::v2f32:   return "v2f32";
  case MVT::v4f32:   return "v4f32";
  case MVT::v2f64:   return "v2f64";
  case MVT::v3i32:   return "v3i32";
  case MVT::v3f32:   return "v3f32";
  }
}

/// getTypeForMVT - This method returns an LLVM type corresponding to the
/// specified MVT.  For integer types, this returns an unsigned type.  Note
/// that this will abort for types that cannot be represented.
const Type *MVT::getTypeForMVT() const {
  switch (V) {
  default:
    assert(isExtended() && "Type is not extended!");
    return LLVMTy;
  case MVT::isVoid:  return Type::VoidTy;
  case MVT::i1:      return Type::Int1Ty;
  case MVT::i8:      return Type::Int8Ty;
  case MVT::i16:     return Type::Int16Ty;
  case MVT::i32:     return Type::Int32Ty;
  case MVT::i64:     return Type::Int64Ty;
  case MVT::i128:    return IntegerType::get(128);
  case MVT::f32:     return Type::FloatTy;
  case MVT::f64:     return Type::DoubleTy;
  case MVT::f80:     return Type::X86_FP80Ty;
  case MVT::f128:    return Type::FP128Ty;
  case MVT::ppcf128: return Type::PPC_FP128Ty;
  case MVT::v8i8:    return VectorType::get(Type::Int8Ty, 8);
  case MVT::v4i16:   return VectorType::get(Type::Int16Ty, 4);
  case MVT::v2i32:   return VectorType::get(Type::Int32Ty, 2);
  case MVT::v1i64:   return VectorType::get(Type::Int64Ty, 1);
  case MVT::v16i8:   return VectorType::get(Type::Int8Ty, 16);
  case MVT::v8i16:   return VectorType::get(Type::Int16Ty, 8);
  case MVT::v4i32:   return VectorType::get(Type::Int32Ty, 4);
  case MVT::v2i64:   return VectorType::get(Type::Int64Ty, 2);
  case MVT::v2f32:   return VectorType::get(Type::FloatTy, 2);
  case MVT::v4f32:   return VectorType::get(Type::FloatTy, 4);
  case MVT::v2f64:   return VectorType::get(Type::DoubleTy, 2);
  case MVT::v3i32:   return VectorType::get(Type::Int32Ty, 3);
  case MVT::v3f32:   return VectorType::get(Type::FloatTy, 3);
  }
}

/// getMVT - Return the value type corresponding to the specified type.  This
/// returns all pointers as MVT::iPTR.  If HandleUnknown is true, unknown types
/// are returned as Other, otherwise they are invalid.
MVT MVT::getMVT(const Type *Ty, bool HandleUnknown){
  switch (Ty->getTypeID()) {
  default:
    if (HandleUnknown) return MVT::Other;
    assert(0 && "Unknown type!");
    return MVT::isVoid;
  case Type::VoidTyID:
    return MVT::isVoid;
  case Type::IntegerTyID:
    return getIntegerVT(cast<IntegerType>(Ty)->getBitWidth());
  case Type::FloatTyID:     return MVT::f32;
  case Type::DoubleTyID:    return MVT::f64;
  case Type::X86_FP80TyID:  return MVT::f80;
  case Type::FP128TyID:     return MVT::f128;
  case Type::PPC_FP128TyID: return MVT::ppcf128;
  case Type::PointerTyID:   return MVT::iPTR;
  case Type::VectorTyID: {
    const VectorType *VTy = cast<VectorType>(Ty);
    return getVectorVT(getMVT(VTy->getElementType(), false),
                       VTy->getNumElements());
  }
  }
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "TimerTaskHeap.h"

using namespace decaf;
using namespace decaf::internal;
using namespace decaf::internal::util;

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::~TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
Pointer<TimerTask> TimerTaskHeap::peek() {

    if( heap.empty() ) {
        return Pointer<TimerTask>();
    }

    return heap[0];
}

////////////////////////////////////////////////////////////////////////////////
bool TimerTaskHeap::isEmpty() const {
    return heap.empty();
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::size() const {
    return this->heap.size();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {

    heap.push_back( task );
    upHeap();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::remove( std::size_t pos ) {

    // possible to delete any position of the heap
    if( pos < heap.size() ) {
        heap[pos] = heap.back();
        heap.pop_back();
        downHeap( pos );
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::upHeap() {

    if( heap.size() <= 1 ) {
        return;  // Can't get any higher than the top.
    }

    std::size_t current = heap.size() - 1;
    std::size_t parent = ( current - 1 ) / 2;

    while( heap[current]->when < heap[parent]->when) {

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[parent];
        heap[parent] = tmp;

        // update parent and current positions.
        current = parent;
        parent = ( current - 1 ) / 2;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::downHeap( std::size_t pos ) {

    std::size_t current = pos;
    std::size_t child = 2 * current + 1;

    while( child < heap.size() && !heap.empty() ) {

        // compare the children if they exist
        if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {
            child++;
        }

        // compare selected child with parent
        if( heap[current]->when < heap[child]->when ) {
            break;
        }

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[child];
        heap[child] = tmp;

        // update child and current positions
        current = child;
        child = 2 * current + 1;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::reset() {
    heap.clear();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::adjustMinimum() {
    downHeap( 0 );
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::deleteIfCancelled() {

    std::size_t result = 0;

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i]->cancelled ) {
            result++;
            remove( i );
            // re-try this point
            i--;
        }
    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i] == task ) {
            return i;
        }
    }

    return -1;
}
<commit_msg>64bit OS fix<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "TimerTaskHeap.h"

using namespace decaf;
using namespace decaf::internal;
using namespace decaf::internal::util;

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::~TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
Pointer<TimerTask> TimerTaskHeap::peek() {

    if( heap.empty() ) {
        return Pointer<TimerTask>();
    }

    return heap[0];
}

////////////////////////////////////////////////////////////////////////////////
bool TimerTaskHeap::isEmpty() const {
    return heap.empty();
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::size() const {
    return this->heap.size();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {

    heap.push_back( task );
    upHeap();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::remove( std::size_t pos ) {

    // possible to delete any position of the heap
    if( pos < heap.size() ) {
        heap[pos] = heap.back();
        heap.pop_back();
        downHeap( pos );
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::upHeap() {

    std::size_t current = heap.size() - 1;
    std::size_t parent = ( current - 1 ) / 2;

    while( current != 0 && heap[current]->when < heap[parent]->when) {

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[parent];
        heap[parent] = tmp;

        // update parent and current positions.
        current = parent;
        parent = ( current - 1 ) / 2;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::downHeap( std::size_t pos ) {

    std::size_t current = pos;
    std::size_t child = 2 * current + 1;

    while( child < heap.size() && !heap.empty() ) {

        // compare the children if they exist
        if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {
            child++;
        }

        // compare selected child with parent
        if( heap[current]->when < heap[child]->when ) {
            break;
        }

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[child];
        heap[child] = tmp;

        // update child and current positions
        current = child;
        child = 2 * current + 1;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::reset() {
    heap.clear();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::adjustMinimum() {
    downHeap( 0 );
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::deleteIfCancelled() {

    std::size_t result = 0;

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i]->cancelled ) {
            result++;
            remove( i );
            // re-try this point
            i--;
        }
    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i] == task ) {
            return i;
        }
    }

    return -1;
}
<|endoftext|>


<commit_before>#include "menuinterface.h"
#include <iostream>
using namespace std;

const string DISPLAY_LIST = "1";
const string ADD = "3";
const string SEARCH = "2";
const string REMOVE = "4";

const string SORT_ALPHABET = "1";
const string SORT_ASCENDING_ALPHABET = "2";
const string SORT_BY_YEAR_OF_BIRTH = "3";
const string SORT_BY_ASCENDING_YEAR_OF_BIRTH = "4";
const string SORT_BY_YEAR_OF_DEATH = "5";
const string SORT_BY_AGE = "6";
const string SORT_BY_GENDER = "7";
const string GO_BACK = "0";

const int FIRST_TIME = 0;

const string COMPUTER = "1";
const string SCIENTIST = "2";

void MenuInterface::invalidInput()
{
    cout << endl;
    cout << "Your input was invalid, please try again." << endl;
    cout << endl;
}

void MenuInterface::banner()
{
    system("CLS");
    if(firstTimeBooting == FIRST_TIME)
    {
        cout << endl;
        cout << "       ********************************************" << endl;
        cout << "       *  WELCOME TO THE COMPUTER SCIENTIST LIST  *" << endl;
        cout << "       ********************************************" << endl;
        cout << endl;
        firstTimeBooting = 1;//just something else than 0
    }
    else
    {
        cout << endl;
        cout << "       ********************************************" << endl;
        cout << "       *          COMPUTER SCIENTIST LIST         *" << endl;
        cout << "       ********************************************" << endl;
        cout << endl;
    }

}

void MenuInterface::DisplayMenu()
{
    string choice;

    while(choice != "Q" || choice != "q")
    {
        // GAMLA MENU-IÐ
        /*cout << endl;
        cout << "| 1 | Display the complete list" << endl;
        cout << "| 2 | Search the list for a computer scientist" << endl;
        cout << "| 3 | Add a computer scientist to the list" << endl;
        cout << "| 4 | Remove a computer scientist from the list" << endl;
        cout << "| Q | Exit the program" << endl;
        cout << "Enter your choice here: ";
        cin >> choice;
        cout << endl;*/

        cout << "| 1 | Display either a computer or a scientist" << endl;
        cout << "| 2 | Search the list" << endl;
        cout << "| 3 | Add to the list" << endl;
        cout << "| 4 | Remove from the list" << endl;
        cout << "| Q | Exit the program" << endl;
        cout << "Enter your choice here: ";
        cin >> choice;
        cout << endl;

        if(choice == DISPLAY_LIST || choice == ADD || choice == SEARCH || choice == REMOVE)
        {
            processChoice(choice);
        }
        else if(choice == "Q" || choice == "q")
        {
            return;
        }
        else
        {
            invalidInput();
            banner();
            DisplayMenu();
        }
    }
}

string MenuInterface::subMenu()
{
    string subMenuChoice;
    do
    {
        cout << endl;
        cout << "Choose either:" << endl;
        cout << "1) A computer " << endl;
        cout << "2) A scientist " << endl;

        cin >> subMenuChoice;

        if(subMenuChoice == COMPUTER || subMenuChoice == SCIENTIST)
        {
            return subMenuChoice;
        }
        else
        {
            cout << endl;
            invalidInput();
            cout << endl;
        }
    }while(subMenuChoice != COMPUTER || subMenuChoice != SCIENTIST);

    return subMenuChoice;
}

void MenuInterface::processChoice(const string choice)
{
    string subMenuChoice = subMenu();
    int choiceInt = stoi(choice);
    cout << "| 1 | Display either a computer or a scientist" << endl;
    cout << "| 2 | Search the list" << endl;
    cout << "| 3 | Add to the list" << endl;
    cout << "| 4 | Remove from the list" << endl;

    cout << "1) A computer " << endl;
    cout << "2) A scientist " << endl;

    banner();

    // Computer operations
    if(subMenuChoice == COMPUTER)
    {
        switch (choiceInt)
        {
        case 1:
            //Display computer
            break;
        case 2:
            // Search for a computer"
            break;
        case 3:
               // Add a computer
        break;
        case 4:
            // Remove a computer
            break;
        default:
            invalidInput();
            break;
        }
    }

    // Scientist operations
    else if(subMenuChoice == SCIENTIST)
    {
        switch (choiceInt)
        {
        case 1:
            displayScientists();
            break;
        case 2:
            banner();
            _uL.searchForAPerson();
            break;
        case 3:
            banner();
            _uL.addPerson();
        break;
        case 4:
            banner();
            _uL.removePersonFromList();
            break;
        default:
            invalidInput();
            break;
        }
    }
}

void MenuInterface::displayScientists()
{
    string sortOption;
    _uL.printCompleteList();
    cout << "| 1 | Sort computer scientists by alphabetical order" << endl;
    cout << "| 2 | Sort computer scientists by ascending alphabetical order" << endl;
    cout << "| 3 | Sort computer scientists by year of birth" << endl;
    cout << "| 4 | Sort computer scientists by ascending year of birth" << endl;
    cout << "| 5 | Sort computer scientists by year of death" << endl;
    cout << "| 6 | Sort computer scientists by age" << endl;
    cout << "| 7 | Sort computer scientists by gender" << endl;
    cout << "| 0 | Go back" << endl;
    cout << "Enter your choice here: ";
    cin >> sortOption;
    cout << endl;

    if(sortOption == SORT_ALPHABET)
    {
        banner();
        _uL.sortListAlphabetically();
    }
    else if(sortOption == SORT_BY_YEAR_OF_BIRTH)
    {
        banner();
        _uL.sortListByBirthYear();
    }
    else if(sortOption == SORT_BY_YEAR_OF_DEATH)
    {
        banner();
        _uL.sortListByDeathYear();
    }
    else if(sortOption == SORT_BY_AGE)
    {
        banner();
        _uL.sortListByAge();
    }
    else if(sortOption == SORT_ASCENDING_ALPHABET)
    {
        banner();
        _uL.sortListAlphabeticallyASC();
    }
    else if(sortOption == SORT_BY_ASCENDING_YEAR_OF_BIRTH)
    {
        banner();
        _uL.sortListByBirthYearASC();
    }
    else if(sortOption == SORT_BY_GENDER)
    {
        banner();
        _uL.sortListByGender();
    }
    else if(sortOption == GO_BACK)
    {
        banner();
    }
    else
    {
        banner();
        invalidInput();
    }
}

<commit_msg>menu for scientist now up and running correctly<commit_after>#include "menuinterface.h"
#include <iostream>
using namespace std;

const string DISPLAY_LIST = "1";
const string ADD = "3";
const string SEARCH = "2";
const string REMOVE = "4";

const string SORT_ALPHABET = "1";
const string SORT_ASCENDING_ALPHABET = "2";
const string SORT_BY_YEAR_OF_BIRTH = "3";
const string SORT_BY_ASCENDING_YEAR_OF_BIRTH = "4";
const string SORT_BY_YEAR_OF_DEATH = "5";
const string SORT_BY_AGE = "6";
const string SORT_BY_GENDER = "7";
const string GO_BACK = "0";

const int FIRST_TIME = 0;

const string COMPUTER = "1";
const string SCIENTIST = "2";

void MenuInterface::invalidInput()
{
    cout << endl;
    cout << "Your input was invalid, please try again." << endl;
    cout << endl;
}

void MenuInterface::banner()
{
    system("CLS");
    if(firstTimeBooting == FIRST_TIME)
    {
        cout << endl;
        cout << "       ********************************************" << endl;
        cout << "       *  WELCOME TO THE COMPUTER SCIENTIST LIST  *" << endl;
        cout << "       ********************************************" << endl;
        cout << endl;
        firstTimeBooting = 1;//just something else than 0
    }
    else
    {
        cout << endl;
        cout << "       ********************************************" << endl;
        cout << "       *          COMPUTER SCIENTIST LIST         *" << endl;
        cout << "       ********************************************" << endl;
        cout << endl;
    }

}

void MenuInterface::DisplayMenu()
{
    string choice;

    while(choice != "Q" || choice != "q")
    {
        // GAMLA MENU-IÐ
        /*cout << endl;
        cout << "| 1 | Display the complete list" << endl;
        cout << "| 2 | Search the list for a computer scientist" << endl;
        cout << "| 3 | Add a computer scientist to the list" << endl;
        cout << "| 4 | Remove a computer scientist from the list" << endl;
        cout << "| Q | Exit the program" << endl;
        cout << "Enter your choice here: ";
        cin >> choice;
        cout << endl;*/

        cout << "| 1 | Display either a computer or a scientist" << endl;
        cout << "| 2 | Search the list" << endl;
        cout << "| 3 | Add to the list" << endl;
        cout << "| 4 | Remove from the list" << endl;
        cout << "| Q | Exit the program" << endl;
        cout << "Enter your choice here: ";
        cin >> choice;
        cout << endl;

        if(choice == DISPLAY_LIST || choice == ADD || choice == SEARCH || choice == REMOVE)
        {
            processChoice(choice);
        }
        else if(choice == "Q" || choice == "q")
        {
            return;
        }
        else
        {
            invalidInput();
            banner();
            DisplayMenu();
        }
    }
}

string MenuInterface::subMenu()
{
    string subMenuChoice;
    do
    {
        cout << endl;
        cout << "Choose either:" << endl;
        cout << "1) A computer " << endl;
        cout << "2) A scientist " << endl;

        cin >> subMenuChoice;

        if(subMenuChoice == COMPUTER || subMenuChoice == SCIENTIST)
        {
            return subMenuChoice;
        }
        else
        {
            cout << endl;
            invalidInput();
            cout << endl;
        }
    }while(subMenuChoice != COMPUTER || subMenuChoice != SCIENTIST);

    return subMenuChoice;
}

void MenuInterface::processChoice(const string choice)
{
    string subMenuChoice = subMenu();
    int choiceInt = stoi(choice);
    banner();

    // Computer operations
    if(subMenuChoice == COMPUTER)
    {
        switch (choiceInt)
        {
        case 1:
            //Display computer
            break;
        case 2:
            // Search for a computer"
            break;
        case 3:
               // Add a computer
        break;
        case 4:
            // Remove a computer
            break;
        default:
            invalidInput();
            break;
        }
    }

    // Scientist operations
    else if(subMenuChoice == SCIENTIST)
    {
        switch (choiceInt)
        {
        case 1:
            displayScientists();
            break;
        case 2:
            banner();
            _uL.searchForAPerson();
            break;
        case 3:
            banner();
            _uL.addPerson();
        break;
        case 4:
            banner();
            _uL.removePersonFromList();
            break;
        default:
            invalidInput();
            break;
        }
    }
}

void MenuInterface::displayScientists()
{
    string sortOption;
    _uL.printCompleteList();
    cout << "| 1 | Sort computer scientists by alphabetical order" << endl;
    cout << "| 2 | Sort computer scientists by ascending alphabetical order" << endl;
    cout << "| 3 | Sort computer scientists by year of birth" << endl;
    cout << "| 4 | Sort computer scientists by ascending year of birth" << endl;
    cout << "| 5 | Sort computer scientists by year of death" << endl;
    cout << "| 6 | Sort computer scientists by age" << endl;
    cout << "| 7 | Sort computer scientists by gender" << endl;
    cout << "| 0 | Go back" << endl;
    cout << "Enter your choice here: ";
    cin >> sortOption;
    cout << endl;

    if(sortOption == SORT_ALPHABET)
    {
        banner();
        _uL.sortListAlphabetically();
    }
    else if(sortOption == SORT_BY_YEAR_OF_BIRTH)
    {
        banner();
        _uL.sortListByBirthYear();
    }
    else if(sortOption == SORT_BY_YEAR_OF_DEATH)
    {
        banner();
        _uL.sortListByDeathYear();
    }
    else if(sortOption == SORT_BY_AGE)
    {
        banner();
        _uL.sortListByAge();
    }
    else if(sortOption == SORT_ASCENDING_ALPHABET)
    {
        banner();
        _uL.sortListAlphabeticallyASC();
    }
    else if(sortOption == SORT_BY_ASCENDING_YEAR_OF_BIRTH)
    {
        banner();
        _uL.sortListByBirthYearASC();
    }
    else if(sortOption == SORT_BY_GENDER)
    {
        banner();
        _uL.sortListByGender();
    }
    else if(sortOption == GO_BACK)
    {
        banner();
    }
    else
    {
        banner();
        invalidInput();
    }
}

<|endoftext|>


<commit_before><commit_msg>minicargo - Accept either MINICARGO_RUN_ONCE or MINICARGO_RUNONCE<commit_after><|endoftext|>


<commit_before>#pragma once
#include <engine/gfx/opengl/context.hpp>
#include <engine/gfx/opengl/glsl.hpp>
#include <boost/optional.hpp>

namespace engine::gfx::opengl
{

struct attribute_info
{
  GLint const global_index;
  GLint const num_floats;

  explicit attribute_info(GLint const i, GLint const nf)
    : global_index(i)
    , num_floats(nf)
  {}
};

using optional_attribute = boost::optional<attribute_info>;

struct attribute_list {
  optional_attribute const vertex;
  optional_attribute const color;
  optional_attribute const uv;

  auto num_floats() const
  {
    auto const add = [](auto const& opt) { return opt ? opt->num_floats : 0; };
    return add(this->vertex) + add(this->color) + add(this->uv);
  }
};

class vertex_attribute
{
  GLuint const vao_, vbo_;

  // configure this OpenGL VAO attribute with this linear layout
  attribute_list const list_;

public:
  vertex_attribute(GLuint const vao, GLuint const vbo, attribute_list const& list)
      : vao_(vao)
      , vbo_(vbo)
      , list_(list)
  {
  }

  auto const vao() const { return this->vao_; }
  auto const vbo() const { return this->vbo_; }
  auto vertices() const { return this->list_.vertex; }
  auto colors() const { return this->list_.color; }
  auto uv() const { return this->list_.uv; }

  auto num_floats() const { return this->list_.num_floats(); }
};

auto
make_vertex_attribute(opengl_context const &ctx)
{
  // num floats per attribute
  GLint constexpr nf_vertex = 4; // x, y, z, w
  GLint constexpr nf_color = 4;  // r, g, b, a
  GLint constexpr nf_uv = 2;     // u, v

  // clang-format off
  static attribute_info const vertex_info{VERTEX_ATTRIBUTE_INDEX_OF_POSITION, nf_vertex};
  static attribute_info const color_info {VERTEX_ATTRIBUTE_INDEX_OF_COLOR, nf_color};
  static attribute_info const uv_info    {VERTEX_ATTRIBUTE_INDEX_OF_UV, nf_uv};
  // clang-format on

  // attribute indexes
  attribute_list const list{attribute_info{vertex_info}, attribute_info{color_info}, attribute_info{uv_info}};
  return vertex_attribute{ctx.vao(), ctx.vbo(), std::move(list)};
}

namespace global
{

template <typename L>
auto
set_vertex_attributes(L &logger, vertex_attribute const &va)
{
  vao_bind(va.vao());
  ON_SCOPE_EXIT([]() { vao_unbind(); });

  glBindBuffer(GL_ARRAY_BUFFER, va.vbo());
  ON_SCOPE_EXIT([]() { glBindBuffer(GL_ARRAY_BUFFER, 0); });

  struct skip_context {
    GLsizei const total_component_count;
    GLsizei components_skipped = 0;

    skip_context(GLsizei const c)
        : total_component_count(c)
    {
    }
  };

  skip_context sc{va.num_floats()};
  auto const set_attrib_pointer = [&logger, &sc](auto const& optional_attribute_info)
  {
    if (! optional_attribute_info) {
      return;
    }

    auto const& attribute_info = *optional_attribute_info;
    auto const attribute_index = attribute_info.global_index;
    auto const component_count = attribute_info.num_floats;

    // enable vertex attibute arrays
    glEnableVertexAttribArray(attribute_index);

    static auto constexpr DONT_NORMALIZE_THE_DATA = GL_FALSE;

    // clang-format off
    auto const offset_in_bytes = sc.components_skipped * sizeof(GL_FLOAT);
    auto const stride_in_bytes = sc.total_component_count * sizeof(GL_FLOAT);
    glVertexAttribPointer(
        attribute_index,                             // global index id
        component_count,                             // number of components per attribute
        GL_FLOAT,                                    // data-type of the components
        DONT_NORMALIZE_THE_DATA,                     // don't normalize our data
        stride_in_bytes,                             // byte-offset between consecutive vertex attributes
        reinterpret_cast<GLvoid*>(offset_in_bytes)); // offset from beginning of buffer
    // clang-format on
    sc.components_skipped += component_count;

    GLint enabled = 0;
    glGetVertexAttribiv(attribute_index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &enabled);

    auto const s = fmt::format("%-10d %-10d %-10d %-10s %-10d %-10d %-10d %-10d\n", attribute_index,
                               enabled, component_count, "float", DONT_NORMALIZE_THE_DATA,
                               stride_in_bytes, offset_in_bytes, sc.components_skipped);
    logger.trace(s);
  };

  {
    int max_attribs = 0;
    glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_attribs);
    auto const fmt = fmt::format("maximum number of vertex attributes: '%d'\n", max_attribs);
    logger.trace(fmt);
  }
  {
    auto const fmt = fmt::format("%-10s %-10s %-10s %-10s %-10s %-10s %-10s\n", "index:", "enabled",
                                 "size", "type", "normalized", "stride", "pointer", "num skipped");
    logger.trace(fmt);
  }
  set_attrib_pointer(va.vertices());
  set_attrib_pointer(va.colors());
  set_attrib_pointer(va.uv());
};

} // ns global

} // ns engine::gfx::opengl
<commit_msg>formatter<commit_after>#pragma once
#include <boost/optional.hpp>
#include <engine/gfx/opengl/context.hpp>
#include <engine/gfx/opengl/glsl.hpp>

namespace engine::gfx::opengl
{

struct attribute_info {
  GLint const global_index;
  GLint const num_floats;

  explicit attribute_info(GLint const i, GLint const nf)
      : global_index(i)
      , num_floats(nf)
  {
  }
};

using optional_attribute = boost::optional<attribute_info>;

struct attribute_list {
  optional_attribute const vertex;
  optional_attribute const color;
  optional_attribute const uv;

  auto num_floats() const
  {
    auto const add = [](auto const &opt) { return opt ? opt->num_floats : 0; };
    return add(this->vertex) + add(this->color) + add(this->uv);
  }
};

class vertex_attribute
{
  GLuint const vao_, vbo_;

  // configure this OpenGL VAO attribute with this linear layout
  attribute_list const list_;

public:
  vertex_attribute(GLuint const vao, GLuint const vbo, attribute_list const &list)
      : vao_(vao)
      , vbo_(vbo)
      , list_(list)
  {
  }

  auto const vao() const { return this->vao_; }
  auto const vbo() const { return this->vbo_; }
  auto vertices() const { return this->list_.vertex; }
  auto colors() const { return this->list_.color; }
  auto uv() const { return this->list_.uv; }

  auto num_floats() const { return this->list_.num_floats(); }
};

auto
make_vertex_attribute(opengl_context const &ctx)
{
  // num floats per attribute
  GLint constexpr nf_vertex = 4; // x, y, z, w
  GLint constexpr nf_color = 4;  // r, g, b, a
  GLint constexpr nf_uv = 2;     // u, v

  // clang-format off
  static attribute_info const vertex_info{VERTEX_ATTRIBUTE_INDEX_OF_POSITION, nf_vertex};
  static attribute_info const color_info {VERTEX_ATTRIBUTE_INDEX_OF_COLOR, nf_color};
  static attribute_info const uv_info    {VERTEX_ATTRIBUTE_INDEX_OF_UV, nf_uv};
  // clang-format on

  // attribute indexes
  attribute_list const list{attribute_info{vertex_info}, attribute_info{color_info},
                            attribute_info{uv_info}};
  return vertex_attribute{ctx.vao(), ctx.vbo(), std::move(list)};
}

namespace global
{

template <typename L>
auto
set_vertex_attributes(L &logger, vertex_attribute const &va)
{
  vao_bind(va.vao());
  ON_SCOPE_EXIT([]() { vao_unbind(); });

  glBindBuffer(GL_ARRAY_BUFFER, va.vbo());
  ON_SCOPE_EXIT([]() { glBindBuffer(GL_ARRAY_BUFFER, 0); });

  struct skip_context {
    GLsizei const total_component_count;
    GLsizei components_skipped = 0;

    skip_context(GLsizei const c)
        : total_component_count(c)
    {
    }
  };

  skip_context sc{va.num_floats()};
  auto const set_attrib_pointer = [&logger, &sc](auto const &optional_attribute_info) {
    if (!optional_attribute_info) {
      return;
    }

    auto const &attribute_info = *optional_attribute_info;
    auto const attribute_index = attribute_info.global_index;
    auto const component_count = attribute_info.num_floats;

    // enable vertex attibute arrays
    glEnableVertexAttribArray(attribute_index);

    static auto constexpr DONT_NORMALIZE_THE_DATA = GL_FALSE;

    // clang-format off
    auto const offset_in_bytes = sc.components_skipped * sizeof(GL_FLOAT);
    auto const stride_in_bytes = sc.total_component_count * sizeof(GL_FLOAT);
    glVertexAttribPointer(
        attribute_index,                             // global index id
        component_count,                             // number of components per attribute
        GL_FLOAT,                                    // data-type of the components
        DONT_NORMALIZE_THE_DATA,                     // don't normalize our data
        stride_in_bytes,                             // byte-offset between consecutive vertex attributes
        reinterpret_cast<GLvoid*>(offset_in_bytes)); // offset from beginning of buffer
    // clang-format on
    sc.components_skipped += component_count;

    GLint enabled = 0;
    glGetVertexAttribiv(attribute_index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &enabled);

    auto const s = fmt::format("%-10d %-10d %-10d %-10s %-10d %-10d %-10d %-10d\n", attribute_index,
                               enabled, component_count, "float", DONT_NORMALIZE_THE_DATA,
                               stride_in_bytes, offset_in_bytes, sc.components_skipped);
    logger.trace(s);
  };

  {
    int max_attribs = 0;
    glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_attribs);
    auto const fmt = fmt::format("maximum number of vertex attributes: '%d'\n", max_attribs);
    logger.trace(fmt);
  }
  {
    auto const fmt = fmt::format("%-10s %-10s %-10s %-10s %-10s %-10s %-10s\n", "index:", "enabled",
                                 "size", "type", "normalized", "stride", "pointer", "num skipped");
    logger.trace(fmt);
  }
  set_attrib_pointer(va.vertices());
  set_attrib_pointer(va.colors());
  set_attrib_pointer(va.uv());
};

} // ns global

} // ns engine::gfx::opengl
<|endoftext|>


<commit_before>#ifndef IZENELIB_IR_ZAMBEZI_POSITIONAL_INVERTED_INDEX_HPP
#define IZENELIB_IR_ZAMBEZI_POSITIONAL_INVERTED_INDEX_HPP

#include "IndexBase.hpp"
#include "SegmentPool.hpp"
#include "Dictionary.hpp"
#include "Pointers.hpp"
#include "buffer/PositionalBufferMaps.hpp"
#include "Consts.hpp"
#include <util/compression/int/fastpfor/fastpfor.h>

#include <boost/shared_ptr.hpp>
#include <iostream>
#include <vector>

NS_IZENELIB_IR_BEGIN

namespace Zambezi
{

class PositionalInvertedIndex : public IndexBase
{
public:
    PositionalInvertedIndex(
            IndexType type = NON_POSITIONAL,
            uint32_t maxPoolSize = MAX_POOL_SIZE,
            uint32_t numberOfPools = NUMBER_OF_POOLS,
            uint32_t vocabSize = DEFAULT_VOCAB_SIZE,
            bool reverse = true,
            bool bloomEnabled = true,
            uint32_t nbHash = 3,
            uint32_t bitsPerElement = 8);

    virtual ~PositionalInvertedIndex();

    virtual void save(std::ostream& ostr) const;
    virtual void load(std::istream& istr);

    /// @brief: interface to build Positional zambezi index;
    /// @docid: must be used;
    /// @term_list:
    /// for example: if the title is:"aa bb cc dd aa cc";
    /// then, the term_list is {aa, bb, cc, dd, aa, cc};
    /// @score_list: not use here, just for unify insertDoc interface;
    virtual void insertDoc(uint32_t docid,
                     const std::vector<std::string>& term_list,
                     const std::vector<uint32_t>& score_list);

    virtual void flush();

    /// @algorithm, different search mode;
    /// @term_list, in pair<std::string, int>, infact olny string is used in
    /// this function;
    /// @hits, the max number of hit number;
    /// @search_buffer:is not used here, just for unify interface;
    virtual void retrieve(
            Algorithm algorithm,
            const std::vector<std::pair<std::string, int> >& term_list,
            const FilterBase* filter,
            uint32_t hits,
            std::vector<uint32_t>& docid_list,
            std::vector<float>& score_list) const;

    virtual uint32_t totalDocNum() const;

private:
    void processTermBuffer_(
            std::vector<uint32_t>& docBuffer,
            std::vector<uint32_t>& tfBuffer,
            std::vector<uint32_t>& posBuffer,
            std::vector<uint32_t>& posCountBuffer,
            size_t& tailPointer,
            size_t& headPointer);

    size_t compressAndAppendBlock_(
            FastPFor& codec,
            uint32_t* docBlock,
            uint32_t* tfBlock,
            uint32_t* posBlock,
            uint32_t len,
            uint32_t tflen,
            uint32_t plen,
            size_t lastPointer,
            size_t nextPointer);

    uint32_t decompressDocidBlock_(
            FastPFor& codec,
            uint32_t* outBlock, size_t pointer) const;

    uint32_t decompressTfBlock_(
            FastPFor& codec,
            uint32_t* outBlock, size_t pointer) const;

    uint32_t numberOfPositionBlocks_(size_t pointer) const;

    uint32_t decompressPositionBlock_(
            FastPFor& codec,
            uint32_t* outBlock, size_t pointer) const;

    void decompressPositions_(
            FastPFor& codec,
            uint32_t* tf_list, uint32_t index, size_t pointer, uint32_t* out) const;

    bool containsDocid_(uint32_t docid, size_t& pointer) const;

    void bwandAnd_(
            std::vector<size_t>& headPointers,
            const FilterBase* filter,
            uint32_t hits,
            std::vector<uint32_t>& docid_list) const;

    void bwandOr_(
            std::vector<size_t>& headPointers,
            const std::vector<float>& UB,
            const FilterBase* filter,
            uint32_t hits,
            std::vector<uint32_t>& docid_list,
            std::vector<float>& score_list) const;

    void wand_(
            std::vector<size_t>& headPointers,
            const std::vector<uint32_t>& df,
            const std::vector<float>& UB,
            const std::vector<uint32_t>& docLen,
            const FilterBase* filter,
            uint32_t totalDocs,
            float avgDocLen,
            uint32_t hits,
            bool hasTf,
            std::vector<uint32_t>& docid_list,
            std::vector<float>& score_list) const;

    void intersectSvS_(
            std::vector<size_t>& headPointers,
            const FilterBase* filter,
            uint32_t minDf,
            uint32_t hits,
            std::vector<uint32_t>& docid_list) const;

    bool iterateSegment_(
            FastPFor& codec,
            uint32_t* block,
            uint32_t& count, uint32_t& index, size_t& pointer,
            uint32_t pivot) const;

    bool gallopSearch_(
            const uint32_t* block,
            uint32_t count,
            uint32_t& index,
            uint32_t pivot) const;

    void intersectPostingsLists_(
            FastPFor& codec,
            const FilterBase* filter,
            size_t pointer0, size_t pointer1,
            std::vector<uint32_t>& docid_list) const;

    void intersectSetPostingsList_(
            FastPFor& codec,
            size_t pointer,
            std::vector<uint32_t>& docid_list) const;

private:
    IndexType type_;
    PositionalBufferMaps buffer_;
    SegmentPool pool_;
    Dictionary<std::string> dictionary_;
    Pointers pointers_;

    // if Bloom filters enabled
    bool bloomEnabled_;
    uint32_t nbHash_;
    uint32_t bitsPerElement_;

    FastPFor codec_;

    static const size_t BUFFER_SIZE = 4096;
    uint32_t segment_[BUFFER_SIZE];
};

}

NS_IZENELIB_IR_END

#endif
<commit_msg>Reduce the false positive in bwand_and of zambezi position index.<commit_after>#ifndef IZENELIB_IR_ZAMBEZI_POSITIONAL_INVERTED_INDEX_HPP
#define IZENELIB_IR_ZAMBEZI_POSITIONAL_INVERTED_INDEX_HPP

#include "IndexBase.hpp"
#include "SegmentPool.hpp"
#include "Dictionary.hpp"
#include "Pointers.hpp"
#include "buffer/PositionalBufferMaps.hpp"
#include "Consts.hpp"
#include <util/compression/int/fastpfor/fastpfor.h>

#include <boost/shared_ptr.hpp>
#include <iostream>
#include <vector>

NS_IZENELIB_IR_BEGIN

namespace Zambezi
{

class PositionalInvertedIndex : public IndexBase
{
public:
    PositionalInvertedIndex(
            IndexType type = NON_POSITIONAL,
            uint32_t maxPoolSize = MAX_POOL_SIZE,
            uint32_t numberOfPools = NUMBER_OF_POOLS,
            uint32_t vocabSize = DEFAULT_VOCAB_SIZE,
            bool reverse = true,
            bool bloomEnabled = true,
            uint32_t nbHash = 3,
            uint32_t bitsPerElement = 16);

    virtual ~PositionalInvertedIndex();

    virtual void save(std::ostream& ostr) const;
    virtual void load(std::istream& istr);

    /// @brief: interface to build Positional zambezi index;
    /// @docid: must be used;
    /// @term_list:
    /// for example: if the title is:"aa bb cc dd aa cc";
    /// then, the term_list is {aa, bb, cc, dd, aa, cc};
    /// @score_list: not use here, just for unify insertDoc interface;
    virtual void insertDoc(uint32_t docid,
                     const std::vector<std::string>& term_list,
                     const std::vector<uint32_t>& score_list);

    virtual void flush();

    /// @algorithm, different search mode;
    /// @term_list, in pair<std::string, int>, infact olny string is used in
    /// this function;
    /// @hits, the max number of hit number;
    /// @search_buffer:is not used here, just for unify interface;
    virtual void retrieve(
            Algorithm algorithm,
            const std::vector<std::pair<std::string, int> >& term_list,
            const FilterBase* filter,
            uint32_t hits,
            std::vector<uint32_t>& docid_list,
            std::vector<float>& score_list) const;

    virtual uint32_t totalDocNum() const;

private:
    void processTermBuffer_(
            std::vector<uint32_t>& docBuffer,
            std::vector<uint32_t>& tfBuffer,
            std::vector<uint32_t>& posBuffer,
            std::vector<uint32_t>& posCountBuffer,
            size_t& tailPointer,
            size_t& headPointer);

    size_t compressAndAppendBlock_(
            FastPFor& codec,
            uint32_t* docBlock,
            uint32_t* tfBlock,
            uint32_t* posBlock,
            uint32_t len,
            uint32_t tflen,
            uint32_t plen,
            size_t lastPointer,
            size_t nextPointer);

    uint32_t decompressDocidBlock_(
            FastPFor& codec,
            uint32_t* outBlock, size_t pointer) const;

    uint32_t decompressTfBlock_(
            FastPFor& codec,
            uint32_t* outBlock, size_t pointer) const;

    uint32_t numberOfPositionBlocks_(size_t pointer) const;

    uint32_t decompressPositionBlock_(
            FastPFor& codec,
            uint32_t* outBlock, size_t pointer) const;

    void decompressPositions_(
            FastPFor& codec,
            uint32_t* tf_list, uint32_t index, size_t pointer, uint32_t* out) const;

    bool containsDocid_(uint32_t docid, size_t& pointer) const;

    void bwandAnd_(
            std::vector<size_t>& headPointers,
            const FilterBase* filter,
            uint32_t hits,
            std::vector<uint32_t>& docid_list) const;

    void bwandOr_(
            std::vector<size_t>& headPointers,
            const std::vector<float>& UB,
            const FilterBase* filter,
            uint32_t hits,
            std::vector<uint32_t>& docid_list,
            std::vector<float>& score_list) const;

    void wand_(
            std::vector<size_t>& headPointers,
            const std::vector<uint32_t>& df,
            const std::vector<float>& UB,
            const std::vector<uint32_t>& docLen,
            const FilterBase* filter,
            uint32_t totalDocs,
            float avgDocLen,
            uint32_t hits,
            bool hasTf,
            std::vector<uint32_t>& docid_list,
            std::vector<float>& score_list) const;

    void intersectSvS_(
            std::vector<size_t>& headPointers,
            const FilterBase* filter,
            uint32_t minDf,
            uint32_t hits,
            std::vector<uint32_t>& docid_list) const;

    bool iterateSegment_(
            FastPFor& codec,
            uint32_t* block,
            uint32_t& count, uint32_t& index, size_t& pointer,
            uint32_t pivot) const;

    bool gallopSearch_(
            const uint32_t* block,
            uint32_t count,
            uint32_t& index,
            uint32_t pivot) const;

    void intersectPostingsLists_(
            FastPFor& codec,
            const FilterBase* filter,
            size_t pointer0, size_t pointer1,
            std::vector<uint32_t>& docid_list) const;

    void intersectSetPostingsList_(
            FastPFor& codec,
            size_t pointer,
            std::vector<uint32_t>& docid_list) const;

private:
    IndexType type_;
    PositionalBufferMaps buffer_;
    SegmentPool pool_;
    Dictionary<std::string> dictionary_;
    Pointers pointers_;

    // if Bloom filters enabled
    bool bloomEnabled_;
    uint32_t nbHash_;
    uint32_t bitsPerElement_;

    FastPFor codec_;

    static const size_t BUFFER_SIZE = 4096;
    uint32_t segment_[BUFFER_SIZE];
};

}

NS_IZENELIB_IR_END

#endif
<|endoftext|>


<commit_before>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and         *
* Martin Renou                                                             *
* Copyright (c) QuantStack                                                 *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

// Simplified version of boost.predef

#ifndef XSIMD_INSTRUCTION_SET_HPP
#define XSIMD_INSTRUCTION_SET_HPP

/******************
 * VERSION NUMBER *
 ******************/

// major number can be in [0, 99]
// minor number can be in [0, 99]
// patch number can be in [0, 999999]
#define XSIMD_VERSION_NUMBER(major, minor, patch) \
    ((((major) % 100) * 10000000) + (((minor) % 100) * 100000) + ((patch) % 100000))

#define XSIMD_VERSION_NUMBER_NOT_AVAILABLE \
    XSIMD_VERSION_NUMBER(0, 0, 0)

#define XSIMD_VERSION_NUMBER_AVAILABLE \
    XSIMD_VERSION_NUMBER(0, 0, 1)

/*************************
 * CLEAR INSTRUCTION SET *
 *************************/

#undef XSIMD_X86_INSTR_SET
#undef XSIMD_X86_INSTR_SET_AVAILABLE

#undef XSIMD_X86_AMD_INSTR_SET
#undef XSIMD_X86_AMD_INSTR_SET_AVAILABLE

#undef XSIMD_PPC_INSTR_SET
#undef XSIMD_PPC_INSTR_SET_AVAILABLE

#undef XSIMD_ARM_INSTR_SET
#undef XSIMD_ARM_INSTR_SET_AVAILABLE

/**********************
 * USER CONFIGURATION *
 **********************/

#ifdef XSIMD_FORCE_X86_INSTR_SET
    #define XSIMD_X86_INSTR_SET XSIMD_FORCE_X86_INSTR_SET
    #define XSIMD_X86_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing X86 instruction set")
    #else
        #warning "Forcing X86 instruction set"
    #endif
#elif defined(XSIMD_FORCE_X86_AMD_INSTR_SET)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_FORCE_X86_AMD_INSTR_SET
    #define XSIMD_X86_AMD_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing X86 AMD instruction set")
    #else
        #warning "Forcing X86 AMD instruction set"
    #endif
#elif defined(XSIMD_FORCE_PPC_INSTR_SET)
    #define XSIMD_PPC_INSTR_SET XSIMD_FORCE_PPC_INSTR_SET
    #define XSIMD_PPC_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing PPC instruction set")
    #else
        #warning "Forcing PPC instruction set"
    #endif
#elif defined(XSIMD_FORCE_ARM_INSTR_SET)
    #define XSIMD_ARM_INSTR_SET XSIMD_FORCE_ARM_INSTR_SET
    #define XSIMD_ARM_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing ARM instruction set")
    #else
        #warning "Forcing ARM instruction set"
    #endif
#endif

/***********************
 * X86 INSTRUCTION SET *
 ***********************/

#define XSIMD_X86_SSE_VERSION XSIMD_VERSION_NUMBER(1, 0, 0)
#define XSIMD_X86_SSE2_VERSION XSIMD_VERSION_NUMBER(2, 0, 0)
#define XSIMD_X86_SSE3_VERSION XSIMD_VERSION_NUMBER(3, 0, 0)
#define XSIMD_X86_SSSE3_VERSION XSIMD_VERSION_NUMBER(3, 1, 0)
#define XSIMD_X86_SSE4_1_VERSION XSIMD_VERSION_NUMBER(4, 1, 0)
#define XSIMD_X86_SSE4_2_VERSION XSIMD_VERSION_NUMBER(4, 2, 0)
#define XSIMD_X86_AVX_VERSION XSIMD_VERSION_NUMBER(5, 0, 0)
#define XSIMD_X86_FMA3_VERSION XSIMD_VERSION_NUMBER(5, 2, 0)
#define XSIMD_X86_AVX2_VERSION XSIMD_VERSION_NUMBER(5, 3, 0)
#define XSIMD_X86_AVX512_VERSION XSIMD_VERSION_NUMBER(6, 0, 0)
#define XSIMD_X86_MIC_VERSION XSIMD_VERSION_NUMBER(9, 0, 0)

#if !defined(XSIMD_X86_INSTR_SET) && defined(__MIC__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_MIC_VERSION
#endif

// AVX512 instructions are supported starting with gcc 6
// see https://www.gnu.org/software/gcc/gcc-6/changes.html
#if !defined(XSIMD_X86_INSTR_SET) && (defined(__AVX512__) || defined(__KNCNI__) || defined(__AVX512F__)\
    && (!defined(__GNUC__) || __GNUC__ >= 6))
    #define XSIMD_X86_INSTR_SET XSIMD_X86_AVX512_VERSION

    #if defined(__AVX512VL__)
        #define XSIMD_AVX512VL_AVAILABLE 1
    #endif

    #if defined(__AVX512DQ__)
        #define XSIMD_AVX512DQ_AVAILABLE 1
    #endif

    #if defined(__AVX512BW__)
        #define XSIMD_AVX512BW_AVAILABLE 1
    #endif

    #if __GNUC__ == 6
        #define XSIMD_AVX512_SHIFT_INTRINSICS_IMM_ONLY 1
    #endif
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__AVX2__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_AVX2_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__FMA__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_FMA3_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__AVX__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_AVX_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSE4_2__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE4_2_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSE4_1__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE4_1_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSSE3__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSSE3_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSE3__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE3_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && (defined(__SSE2__) || defined(__x86_64__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2))
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE2_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && (defined(__SSE__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 1))
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE_VERSION
#endif

#if !(defined XSIMD_X86_INSTR_SET)
    #define XSIMD_X86_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    #define XSIMD_X86_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

/***************************
 * X86_AMD INSTRUCTION SET *
 ***************************/

#define XSIMD_X86_AMD_SSE4A_VERSION XSIMD_VERSION_NUMBER(4, 0, 0)
#define XSIMD_X86_AMD_FMA4_VERSION XSIMD_VERSION_NUMBER(5, 1, 0)
#define XSIMD_X86_AMD_XOP_VERSION XSIMD_VERSION_NUMBER(5, 1, 1)

#if !defined(XSIMD_X86_AMD_INSTR_SET) && defined(__XOP__)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_AMD_XOP_VERSION
#endif

#if !defined(XSIMD_X86_AMD_INSTR_SET) && defined(__FMA4__)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_AMD_FMA4_VERSION
#endif

#if !defined(XSIMD_X86_AMD_INSTR_SET) && defined(__SSE4A__)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_AMD_SSE4A_VERSION
#endif

#if !defined(XSIMD_X86_AMD_INSTR_SET)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    // X86_AMD implies X86
    #if XSIMD_X86_INSTR_SET > XSIMD_X86_AMD_INSTR_SET
        #undef XSIMD_X86_AMD_INSTR_SET
        #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_INSTR_SET
    #endif
    #define XSIMD_X86_AMD_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

/***********************
 * PPC INSTRUCTION SET *
 ***********************/

// We haven't implemented any support for PPC, so we should
// not enable detection for this instructoin set
/*#define XSIMD_PPC_VMX_VERSION XSIMD_VERSION_NUMBER(1, 0, 0)
#define XSIMD_PPC_VSX_VERSION XSIMD_VERSION_NUMBER(1, 1, 0)
#define XSIMD_PPC_QPX_VERSION XSIMD_VERSION_NUMBER(2, 0, 0)

#if !defined(XSIMD_PPC_INSTR_SET) && defined(__VECTOR4DOUBLE__)
    #define XSIMD_PPC_INSTR_SET XSIMD_PPC_QPX_VERSION
#endif

#if !defined(XSIMD_PPC_INSTR_SET) && defined(__VSX__)
    #define XSIMD_PPC_INSTR_SET XSIMD_PPC_VSX_VERSION
#endif

#if !defined(XSIMD_PPC_INSTR_SET) && (defined(__ALTIVEC__) || defined(__VEC__))
    #define XSIMD_PPC_INSTR_SET XSIMD_PPC_VMX_VERSION
#endif

#if !defined(XSIMD_PPC_INSTR_SET)
    #define XSIMD_PPC_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    #define XSIMD_PPC_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif*/

/***********************
 * ARM INSTRUCTION SET *
 ***********************/

#define XSIMD_ARM7_NEON_VERSION XSIMD_VERSION_NUMBER(7, 0, 0)
#define XSIMD_ARM8_32_NEON_VERSION XSIMD_VERSION_NUMBER(8, 0, 0)
#define XSIMD_ARM8_64_NEON_VERSION XSIMD_VERSION_NUMBER(8, 1, 0)

// TODO __ARM_FEATURE_FMA
#if !defined(XSIMD_ARM_INSTR_SET) && (defined(__ARM_NEON))
    #if __ARM_ARCH >= 8
        #if defined(__aarch64__)
            #define XSIMD_ARM_INSTR_SET XSIMD_ARM8_64_NEON_VERSION
        #else
            #define XSIMD_ARM_INSTR_SET XSIMD_ARM8_32_NEON_VERSION
        #endif
    #elif __ARM_ARCH >= 7
        #define XSIMD_ARM_INSTR_SET XSIMD_ARM7_NEON_VERSION
    #else
        static_assert("NEON instruction set not supported.", false);
    #endif
#endif

#if !defined(XSIMD_ARM_INSTR_SET)
    #define XSIMD_ARM_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    #define XSIMD_ARM_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

/***************************
 * GENERIC INSTRUCTION SET *
 ***************************/

#undef XSIMD_INSTR_SET
#undef XSIMD_INSTR_SET_AVAILABLE

#if defined(XSIMD_X86_AMD_AVAILABLE)
    #if XSIMD_X86_INSTR_SET > XSIMD_X86_AMD_INSTR_SET
        #define XSIMD_INSTR_SET XSIMD_X86_INSTR_SET
    #else
        #define XSIMD_INSTR_SET XSIMD_X86_AMD_INSTR_SET
    #endif
#endif

#if !defined(XSIMD_INSTR_SET) && defined(XSIMD_X86_INSTR_SET_AVAILABLE)
    #define XSIMD_INSTR_SET XSIMD_X86_INSTR_SET
#endif

#if !defined(XSIMD_INSTR_SET) && defined(XSIMD_PPC_INSTR_SET_AVAILABLE)
    #define XSIMD_INSTR_SET XSIMD_PPC_INSTR_SET
#endif

#if !defined(XSIMD_INSTR_SET) && defined(XSIMD_ARM_INSTR_SET_AVAILABLE)
    #define XSIMD_INSTR_SET XSIMD_ARM_INSTR_SET
#endif

#if !defined(XSIMD_INSTR_SET)
    #define XSIMD_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#elif XSIMD_INSTR_SET != XSIMD_VERSION_NUMBER_NOT_AVAILABLE
    #define XSIMD_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

#endif
<commit_msg>fix static_assert syntax error and use fallback mode when XSIMD_ENABLE_FALLBACK enabled<commit_after>/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and         *
* Martin Renou                                                             *
* Copyright (c) QuantStack                                                 *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

// Simplified version of boost.predef

#ifndef XSIMD_INSTRUCTION_SET_HPP
#define XSIMD_INSTRUCTION_SET_HPP

/******************
 * VERSION NUMBER *
 ******************/

// major number can be in [0, 99]
// minor number can be in [0, 99]
// patch number can be in [0, 999999]
#define XSIMD_VERSION_NUMBER(major, minor, patch) \
    ((((major) % 100) * 10000000) + (((minor) % 100) * 100000) + ((patch) % 100000))

#define XSIMD_VERSION_NUMBER_NOT_AVAILABLE \
    XSIMD_VERSION_NUMBER(0, 0, 0)

#define XSIMD_VERSION_NUMBER_AVAILABLE \
    XSIMD_VERSION_NUMBER(0, 0, 1)

/*************************
 * CLEAR INSTRUCTION SET *
 *************************/

#undef XSIMD_X86_INSTR_SET
#undef XSIMD_X86_INSTR_SET_AVAILABLE

#undef XSIMD_X86_AMD_INSTR_SET
#undef XSIMD_X86_AMD_INSTR_SET_AVAILABLE

#undef XSIMD_PPC_INSTR_SET
#undef XSIMD_PPC_INSTR_SET_AVAILABLE

#undef XSIMD_ARM_INSTR_SET
#undef XSIMD_ARM_INSTR_SET_AVAILABLE

/**********************
 * USER CONFIGURATION *
 **********************/

#ifdef XSIMD_FORCE_X86_INSTR_SET
    #define XSIMD_X86_INSTR_SET XSIMD_FORCE_X86_INSTR_SET
    #define XSIMD_X86_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing X86 instruction set")
    #else
        #warning "Forcing X86 instruction set"
    #endif
#elif defined(XSIMD_FORCE_X86_AMD_INSTR_SET)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_FORCE_X86_AMD_INSTR_SET
    #define XSIMD_X86_AMD_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing X86 AMD instruction set")
    #else
        #warning "Forcing X86 AMD instruction set"
    #endif
#elif defined(XSIMD_FORCE_PPC_INSTR_SET)
    #define XSIMD_PPC_INSTR_SET XSIMD_FORCE_PPC_INSTR_SET
    #define XSIMD_PPC_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing PPC instruction set")
    #else
        #warning "Forcing PPC instruction set"
    #endif
#elif defined(XSIMD_FORCE_ARM_INSTR_SET)
    #define XSIMD_ARM_INSTR_SET XSIMD_FORCE_ARM_INSTR_SET
    #define XSIMD_ARM_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
    #ifdef _MSC_VER
        #pragma message("Warning: Forcing ARM instruction set")
    #else
        #warning "Forcing ARM instruction set"
    #endif
#endif

/***********************
 * X86 INSTRUCTION SET *
 ***********************/

#define XSIMD_X86_SSE_VERSION XSIMD_VERSION_NUMBER(1, 0, 0)
#define XSIMD_X86_SSE2_VERSION XSIMD_VERSION_NUMBER(2, 0, 0)
#define XSIMD_X86_SSE3_VERSION XSIMD_VERSION_NUMBER(3, 0, 0)
#define XSIMD_X86_SSSE3_VERSION XSIMD_VERSION_NUMBER(3, 1, 0)
#define XSIMD_X86_SSE4_1_VERSION XSIMD_VERSION_NUMBER(4, 1, 0)
#define XSIMD_X86_SSE4_2_VERSION XSIMD_VERSION_NUMBER(4, 2, 0)
#define XSIMD_X86_AVX_VERSION XSIMD_VERSION_NUMBER(5, 0, 0)
#define XSIMD_X86_FMA3_VERSION XSIMD_VERSION_NUMBER(5, 2, 0)
#define XSIMD_X86_AVX2_VERSION XSIMD_VERSION_NUMBER(5, 3, 0)
#define XSIMD_X86_AVX512_VERSION XSIMD_VERSION_NUMBER(6, 0, 0)
#define XSIMD_X86_MIC_VERSION XSIMD_VERSION_NUMBER(9, 0, 0)

#if !defined(XSIMD_X86_INSTR_SET) && defined(__MIC__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_MIC_VERSION
#endif

// AVX512 instructions are supported starting with gcc 6
// see https://www.gnu.org/software/gcc/gcc-6/changes.html
#if !defined(XSIMD_X86_INSTR_SET) && (defined(__AVX512__) || defined(__KNCNI__) || defined(__AVX512F__)\
    && (!defined(__GNUC__) || __GNUC__ >= 6))
    #define XSIMD_X86_INSTR_SET XSIMD_X86_AVX512_VERSION

    #if defined(__AVX512VL__)
        #define XSIMD_AVX512VL_AVAILABLE 1
    #endif

    #if defined(__AVX512DQ__)
        #define XSIMD_AVX512DQ_AVAILABLE 1
    #endif

    #if defined(__AVX512BW__)
        #define XSIMD_AVX512BW_AVAILABLE 1
    #endif

    #if __GNUC__ == 6
        #define XSIMD_AVX512_SHIFT_INTRINSICS_IMM_ONLY 1
    #endif
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__AVX2__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_AVX2_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__FMA__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_FMA3_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__AVX__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_AVX_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSE4_2__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE4_2_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSE4_1__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE4_1_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSSE3__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSSE3_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && defined(__SSE3__)
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE3_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && (defined(__SSE2__) || defined(__x86_64__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2))
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE2_VERSION
#endif

#if !defined(XSIMD_X86_INSTR_SET) && (defined(__SSE__) || defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 1))
    #define XSIMD_X86_INSTR_SET XSIMD_X86_SSE_VERSION
#endif

#if !(defined XSIMD_X86_INSTR_SET)
    #define XSIMD_X86_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    #define XSIMD_X86_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

/***************************
 * X86_AMD INSTRUCTION SET *
 ***************************/

#define XSIMD_X86_AMD_SSE4A_VERSION XSIMD_VERSION_NUMBER(4, 0, 0)
#define XSIMD_X86_AMD_FMA4_VERSION XSIMD_VERSION_NUMBER(5, 1, 0)
#define XSIMD_X86_AMD_XOP_VERSION XSIMD_VERSION_NUMBER(5, 1, 1)

#if !defined(XSIMD_X86_AMD_INSTR_SET) && defined(__XOP__)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_AMD_XOP_VERSION
#endif

#if !defined(XSIMD_X86_AMD_INSTR_SET) && defined(__FMA4__)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_AMD_FMA4_VERSION
#endif

#if !defined(XSIMD_X86_AMD_INSTR_SET) && defined(__SSE4A__)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_AMD_SSE4A_VERSION
#endif

#if !defined(XSIMD_X86_AMD_INSTR_SET)
    #define XSIMD_X86_AMD_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    // X86_AMD implies X86
    #if XSIMD_X86_INSTR_SET > XSIMD_X86_AMD_INSTR_SET
        #undef XSIMD_X86_AMD_INSTR_SET
        #define XSIMD_X86_AMD_INSTR_SET XSIMD_X86_INSTR_SET
    #endif
    #define XSIMD_X86_AMD_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

/***********************
 * PPC INSTRUCTION SET *
 ***********************/

// We haven't implemented any support for PPC, so we should
// not enable detection for this instructoin set
/*#define XSIMD_PPC_VMX_VERSION XSIMD_VERSION_NUMBER(1, 0, 0)
#define XSIMD_PPC_VSX_VERSION XSIMD_VERSION_NUMBER(1, 1, 0)
#define XSIMD_PPC_QPX_VERSION XSIMD_VERSION_NUMBER(2, 0, 0)

#if !defined(XSIMD_PPC_INSTR_SET) && defined(__VECTOR4DOUBLE__)
    #define XSIMD_PPC_INSTR_SET XSIMD_PPC_QPX_VERSION
#endif

#if !defined(XSIMD_PPC_INSTR_SET) && defined(__VSX__)
    #define XSIMD_PPC_INSTR_SET XSIMD_PPC_VSX_VERSION
#endif

#if !defined(XSIMD_PPC_INSTR_SET) && (defined(__ALTIVEC__) || defined(__VEC__))
    #define XSIMD_PPC_INSTR_SET XSIMD_PPC_VMX_VERSION
#endif

#if !defined(XSIMD_PPC_INSTR_SET)
    #define XSIMD_PPC_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    #define XSIMD_PPC_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif*/

/***********************
 * ARM INSTRUCTION SET *
 ***********************/

#define XSIMD_ARM7_NEON_VERSION XSIMD_VERSION_NUMBER(7, 0, 0)
#define XSIMD_ARM8_32_NEON_VERSION XSIMD_VERSION_NUMBER(8, 0, 0)
#define XSIMD_ARM8_64_NEON_VERSION XSIMD_VERSION_NUMBER(8, 1, 0)

// TODO __ARM_FEATURE_FMA
#if !defined(XSIMD_ARM_INSTR_SET) && (defined(__ARM_NEON))
    #if __ARM_ARCH >= 8
        #if defined(__aarch64__)
            #define XSIMD_ARM_INSTR_SET XSIMD_ARM8_64_NEON_VERSION
        #else
            #define XSIMD_ARM_INSTR_SET XSIMD_ARM8_32_NEON_VERSION
        #endif
    #elif __ARM_ARCH >= 7
        #define XSIMD_ARM_INSTR_SET XSIMD_ARM7_NEON_VERSION
    #elif defined(XSIMD_ENABLE_FALLBACK)
        #warning "NEON instruction set not supported, using fallback mode."
    #else
        static_assert(false, "NEON instruction set not supported.");
    #endif
#endif

#if !defined(XSIMD_ARM_INSTR_SET)
    #define XSIMD_ARM_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#else
    #define XSIMD_ARM_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

/***************************
 * GENERIC INSTRUCTION SET *
 ***************************/

#undef XSIMD_INSTR_SET
#undef XSIMD_INSTR_SET_AVAILABLE

#if defined(XSIMD_X86_AMD_AVAILABLE)
    #if XSIMD_X86_INSTR_SET > XSIMD_X86_AMD_INSTR_SET
        #define XSIMD_INSTR_SET XSIMD_X86_INSTR_SET
    #else
        #define XSIMD_INSTR_SET XSIMD_X86_AMD_INSTR_SET
    #endif
#endif

#if !defined(XSIMD_INSTR_SET) && defined(XSIMD_X86_INSTR_SET_AVAILABLE)
    #define XSIMD_INSTR_SET XSIMD_X86_INSTR_SET
#endif

#if !defined(XSIMD_INSTR_SET) && defined(XSIMD_PPC_INSTR_SET_AVAILABLE)
    #define XSIMD_INSTR_SET XSIMD_PPC_INSTR_SET
#endif

#if !defined(XSIMD_INSTR_SET) && defined(XSIMD_ARM_INSTR_SET_AVAILABLE)
    #define XSIMD_INSTR_SET XSIMD_ARM_INSTR_SET
#endif

#if !defined(XSIMD_INSTR_SET)
    #define XSIMD_INSTR_SET XSIMD_VERSION_NUMBER_NOT_AVAILABLE
#elif XSIMD_INSTR_SET != XSIMD_VERSION_NUMBER_NOT_AVAILABLE
    #define XSIMD_INSTR_SET_AVAILABLE XSIMD_VERSION_NUMBER_AVAILABLE
#endif

#endif
<|endoftext|>


<commit_before>/**
 * @file llfloaterconversationpreview.cpp
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llconversationlog.h"
#include "llfloaterconversationpreview.h"
#include "llimview.h"
#include "lllineeditor.h"
#include "llfloaterimnearbychat.h"
#include "llspinctrl.h"
#include "lltrans.h"

const std::string LL_FCP_COMPLETE_NAME("complete_name");
const std::string LL_FCP_ACCOUNT_NAME("user_name");

LLFloaterConversationPreview::LLFloaterConversationPreview(const LLSD& session_id)
:	LLFloater(session_id),
	mChatHistory(NULL),
	mSessionID(session_id.asUUID()),
	mCurrentPage(0),
	mPageSize(gSavedSettings.getS32("ConversationHistoryPageSize")),
	mAccountName(session_id[LL_FCP_ACCOUNT_NAME]),
	mCompleteName(session_id[LL_FCP_COMPLETE_NAME])
{
}

BOOL LLFloaterConversationPreview::postBuild()
{
	mChatHistory = getChild<LLChatHistory>("chat_history");
	LLLoadHistoryThread::setLoadEndSignal(boost::bind(&LLFloaterConversationPreview::SetPages, this, _1, _2));

	const LLConversation* conv = LLConversationLog::instance().getConversation(mSessionID);
	std::string name;
	std::string file;

	if (mAccountName != "")
	{
		name = mCompleteName;
		file = mAccountName;
	}
	else if (mSessionID != LLUUID::null && conv)
	{
		name = conv->getConversationName();
		file = conv->getHistoryFileName();
	}
	else
	{
		name = LLTrans::getString("NearbyChatTitle");
		file = "chat";
	}
	mChatHistoryFileName = file;
	LLStringUtil::format_map_t args;
	args["[NAME]"] = name;
	std::string title = getString("Title", args);
	setTitle(title);

	LLSD load_params;
	load_params["load_all_history"] = true;
	load_params["cut_off_todays_date"] = false;

	LLSD loading;
	loading[LL_IM_TEXT] = LLTrans::getString("loading_chat_logs");
	mMessages.push_back(loading);
	mPageSpinner = getChild<LLSpinCtrl>("history_page_spin");
	mPageSpinner->setCommitCallback(boost::bind(&LLFloaterConversationPreview::onMoreHistoryBtnClick, this));
	mPageSpinner->setMinValue(1);
	mPageSpinner->set(1);
	mPageSpinner->setEnabled(false);
	mChatHistoryLoaded = false;
	LLLogChat::startChatHistoryThread(file, load_params);
	return LLFloater::postBuild();
}

void LLFloaterConversationPreview::SetPages(std::list<LLSD>& messages, const std::string& file_name)
{
	if(file_name == mChatHistoryFileName)
	{
		mMessages = messages;

		mCurrentPage = mMessages.size() / mPageSize;
		mPageSpinner->setEnabled(true);
		mPageSpinner->setMaxValue(mCurrentPage+1);
		mPageSpinner->set(mCurrentPage+1);

		std::string total_page_num = llformat("/ %d", mCurrentPage+1);
		getChild<LLTextBox>("page_num_label")->setValue(total_page_num);
		mChatHistoryLoaded = true;

	}

}
void LLFloaterConversationPreview::draw()
{
	if(mChatHistoryLoaded)
	{
		showHistory();
		mChatHistoryLoaded = false;
	}
	LLFloater::draw();
}

void LLFloaterConversationPreview::onOpen(const LLSD& key)
{
	showHistory();
}

void LLFloaterConversationPreview::showHistory()
{
	if (!mMessages.size())
	{
		return;
	}

	mChatHistory->clear();

	std::ostringstream message;
	std::list<LLSD>::const_iterator iter = mMessages.begin();

	int delta = 0;
	if (mCurrentPage)
	{
		int remainder = mMessages.size() % mPageSize;
		delta = (remainder == 0) ? 0 : (mPageSize - remainder);
	}

	std::advance(iter, (mCurrentPage * mPageSize) - delta);

	for (int msg_num = 0; (iter != mMessages.end() && msg_num < mPageSize); ++iter, ++msg_num)
	{
		LLSD msg = *iter;

		LLUUID from_id 		= LLUUID::null;
		std::string time	= msg["time"].asString();
		std::string from	= msg["from"].asString();
		std::string message	= msg["message"].asString();

		if (msg["from_id"].isDefined())
		{
			from_id = msg["from_id"].asUUID();
		}
		else
 		{
			std::string legacy_name = gCacheName->buildLegacyName(from);
 			gCacheName->getUUID(legacy_name, from_id);
 		}

		LLChat chat;
		chat.mFromID = from_id;
		chat.mSessionID = mSessionID;
		chat.mFromName = from;
		chat.mTimeStr = time;
		chat.mChatStyle = CHAT_STYLE_HISTORY;
		chat.mText = message;

		if (from_id.isNull() && SYSTEM_FROM == from)
		{
			chat.mSourceType = CHAT_SOURCE_SYSTEM;

		}
		else if (from_id.isNull())
		{
			chat.mSourceType = LLFloaterIMNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT;
		}

		LLSD chat_args;
		chat_args["use_plain_text_chat_history"] =
						gSavedSettings.getBOOL("PlainTextChatHistory");
		chat_args["show_time"] = gSavedSettings.getBOOL("IMShowTime");
		chat_args["show_names_for_p2p_conv"] = gSavedSettings.getBOOL("IMShowNamesForP2PConv");

		mChatHistory->appendMessage(chat,chat_args);
	}

}

void LLFloaterConversationPreview::onMoreHistoryBtnClick()
{
	mCurrentPage = (int)(mPageSpinner->getValueF32());
	if (--mCurrentPage < 0)
	{
		return;
	}

	showHistory();
}
<commit_msg>MAINT-2938 FIXED [CHUI] crash in LLFloaterConversationPreview::showHistory()<commit_after>/**
 * @file llfloaterconversationpreview.cpp
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llconversationlog.h"
#include "llfloaterconversationpreview.h"
#include "llimview.h"
#include "lllineeditor.h"
#include "llfloaterimnearbychat.h"
#include "llspinctrl.h"
#include "lltrans.h"

const std::string LL_FCP_COMPLETE_NAME("complete_name");
const std::string LL_FCP_ACCOUNT_NAME("user_name");

LLFloaterConversationPreview::LLFloaterConversationPreview(const LLSD& session_id)
:	LLFloater(session_id),
	mChatHistory(NULL),
	mSessionID(session_id.asUUID()),
	mCurrentPage(0),
	mPageSize(gSavedSettings.getS32("ConversationHistoryPageSize")),
	mAccountName(session_id[LL_FCP_ACCOUNT_NAME]),
	mCompleteName(session_id[LL_FCP_COMPLETE_NAME])
{
}

BOOL LLFloaterConversationPreview::postBuild()
{
	mChatHistory = getChild<LLChatHistory>("chat_history");
	LLLoadHistoryThread::setLoadEndSignal(boost::bind(&LLFloaterConversationPreview::SetPages, this, _1, _2));

	const LLConversation* conv = LLConversationLog::instance().getConversation(mSessionID);
	std::string name;
	std::string file;

	if (mAccountName != "")
	{
		name = mCompleteName;
		file = mAccountName;
	}
	else if (mSessionID != LLUUID::null && conv)
	{
		name = conv->getConversationName();
		file = conv->getHistoryFileName();
	}
	else
	{
		name = LLTrans::getString("NearbyChatTitle");
		file = "chat";
	}
	mChatHistoryFileName = file;
	LLStringUtil::format_map_t args;
	args["[NAME]"] = name;
	std::string title = getString("Title", args);
	setTitle(title);

	LLSD load_params;
	load_params["load_all_history"] = true;
	load_params["cut_off_todays_date"] = false;

	LLSD loading;
	loading[LL_IM_TEXT] = LLTrans::getString("loading_chat_logs");
	mMessages.push_back(loading);
	mPageSpinner = getChild<LLSpinCtrl>("history_page_spin");
	mPageSpinner->setCommitCallback(boost::bind(&LLFloaterConversationPreview::onMoreHistoryBtnClick, this));
	mPageSpinner->setMinValue(1);
	mPageSpinner->set(1);
	mPageSpinner->setEnabled(false);
	mChatHistoryLoaded = false;
	LLLogChat::startChatHistoryThread(file, load_params);
	return LLFloater::postBuild();
}

void LLFloaterConversationPreview::SetPages(std::list<LLSD>& messages, const std::string& file_name)
{
	if(file_name == mChatHistoryFileName)
	{
		mMessages = messages;

		mCurrentPage = mMessages.size() / mPageSize;
		mPageSpinner->setEnabled(true);
		mPageSpinner->setMaxValue(mCurrentPage+1);
		mPageSpinner->set(mCurrentPage+1);

		std::string total_page_num = llformat("/ %d", mCurrentPage+1);
		getChild<LLTextBox>("page_num_label")->setValue(total_page_num);
		mChatHistoryLoaded = true;

	}

}
void LLFloaterConversationPreview::draw()
{
	if(mChatHistoryLoaded)
	{
		showHistory();
		mChatHistoryLoaded = false;
	}
	LLFloater::draw();
}

void LLFloaterConversationPreview::onOpen(const LLSD& key)
{
	showHistory();
}

void LLFloaterConversationPreview::showHistory()
{
	if (!mMessages.size())
	{
		return;
	}

	mChatHistory->clear();

	std::ostringstream message;
	std::list<LLSD>::const_iterator iter = mMessages.begin();

	int delta = 0;
	if (mCurrentPage)
	{
		int remainder = mMessages.size() % mPageSize;
		delta = (remainder == 0) ? 0 : (mPageSize - remainder);
	}

	std::advance(iter, (mCurrentPage * mPageSize) - delta);

	for (int msg_num = 0; (iter != mMessages.end() && msg_num < mPageSize); ++iter, ++msg_num)
	{
		if (iter->size() == 0)
		{
			continue;
		}

		LLSD msg = *iter;

		LLUUID from_id 		= LLUUID::null;
		std::string time	= msg["time"].asString();
		std::string from	= msg["from"].asString();
		std::string message	= msg["message"].asString();

		if (msg["from_id"].isDefined())
		{
			from_id = msg["from_id"].asUUID();
		}
		else
 		{
			std::string legacy_name = gCacheName->buildLegacyName(from);
 			gCacheName->getUUID(legacy_name, from_id);
 		}

		LLChat chat;
		chat.mFromID = from_id;
		chat.mSessionID = mSessionID;
		chat.mFromName = from;
		chat.mTimeStr = time;
		chat.mChatStyle = CHAT_STYLE_HISTORY;
		chat.mText = message;

		if (from_id.isNull() && SYSTEM_FROM == from)
		{
			chat.mSourceType = CHAT_SOURCE_SYSTEM;

		}
		else if (from_id.isNull())
		{
			chat.mSourceType = LLFloaterIMNearbyChat::isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT;
		}

		LLSD chat_args;
		chat_args["use_plain_text_chat_history"] =
						gSavedSettings.getBOOL("PlainTextChatHistory");
		chat_args["show_time"] = gSavedSettings.getBOOL("IMShowTime");
		chat_args["show_names_for_p2p_conv"] = gSavedSettings.getBOOL("IMShowNamesForP2PConv");

		mChatHistory->appendMessage(chat,chat_args);
	}

}

void LLFloaterConversationPreview::onMoreHistoryBtnClick()
{
	mCurrentPage = (int)(mPageSpinner->getValueF32());
	if (--mCurrentPage < 0)
	{
		return;
	}

	showHistory();
}
<|endoftext|>