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

#include "components/translate/core/browser/translate_language_list.h"

#include <set>

#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "components/translate/core/browser/translate_browser_metrics.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "components/translate/core/browser/translate_event_details.h"
#include "components/translate/core/browser/translate_url_fetcher.h"
#include "components/translate/core/browser/translate_url_util.h"
#include "components/translate/core/common/translate_util.h"
#include "net/base/url_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"

namespace translate {

namespace {

// The default list of languages the Google translation server supports.
// We use this list until we receive the list that the server exposes.
// For information, here is the list of languages that Chrome can be run in
// but that the translation server does not support:
// am Amharic
// bn Bengali
// gu Gujarati
// kn Kannada
// ml Malayalam
// mr Marathi
// ta Tamil
// te Telugu
const char* const kDefaultSupportedLanguages[] = {
  "af",     // Afrikaans
  "sq",     // Albanian
  "ar",     // Arabic
  "be",     // Belarusian
  "bg",     // Bulgarian
  "ca",     // Catalan
  "zh-CN",  // Chinese (Simplified)
  "zh-TW",  // Chinese (Traditional)
  "hr",     // Croatian
  "cs",     // Czech
  "da",     // Danish
  "nl",     // Dutch
  "en",     // English
  "eo",     // Esperanto
  "et",     // Estonian
  "tl",     // Filipino
  "fi",     // Finnish
  "fr",     // French
  "gl",     // Galician
  "de",     // German
  "el",     // Greek
  "ht",     // Haitian Creole
  "iw",     // Hebrew
  "hi",     // Hindi
  "hu",     // Hungarian
  "is",     // Icelandic
  "id",     // Indonesian
  "ga",     // Irish
  "it",     // Italian
  "ja",     // Japanese
  "ko",     // Korean
  "lv",     // Latvian
  "lt",     // Lithuanian
  "mk",     // Macedonian
  "ms",     // Malay
  "mt",     // Maltese
  "no",     // Norwegian
  "fa",     // Persian
  "pl",     // Polish
  "pt",     // Portuguese
  "ro",     // Romanian
  "ru",     // Russian
  "sr",     // Serbian
  "sk",     // Slovak
  "sl",     // Slovenian
  "es",     // Spanish
  "sw",     // Swahili
  "sv",     // Swedish
  "th",     // Thai
  "tr",     // Turkish
  "uk",     // Ukrainian
  "vi",     // Vietnamese
  "cy",     // Welsh
  "yi",     // Yiddish
};

// Constant URL string to fetch server supporting language list.
const char kLanguageListFetchPath[] = "translate_a/l?client=chrome&cb=sl";

// Used in kTranslateScriptURL to request supporting languages list including
// "alpha languages".
const char kAlphaLanguageQueryName[] = "alpha";
const char kAlphaLanguageQueryValue[] = "1";

// Represent if the language list updater is disabled.
bool update_is_disabled = false;

// Retry parameter for fetching.
const int kMaxRetryOn5xx = 5;

}  // namespace

// This must be kept in sync with the &cb= value in the kLanguageListFetchURL.
const char TranslateLanguageList::kLanguageListCallbackName[] = "sl(";
const char TranslateLanguageList::kTargetLanguagesKey[] = "tl";
const char TranslateLanguageList::kAlphaLanguagesKey[] = "al";

TranslateLanguageList::TranslateLanguageList()
    : resource_requests_allowed_(false), request_pending_(false) {
  // We default to our hard coded list of languages in
  // |kDefaultSupportedLanguages|. This list will be overriden by a server
  // providing supported langauges list.
  for (size_t i = 0; i < arraysize(kDefaultSupportedLanguages); ++i)
    all_supported_languages_.insert(kDefaultSupportedLanguages[i]);

  if (update_is_disabled)
    return;

  language_list_fetcher_.reset(new TranslateURLFetcher(kFetcherId));
  language_list_fetcher_->set_max_retry_on_5xx(kMaxRetryOn5xx);
}

TranslateLanguageList::~TranslateLanguageList() {}

void TranslateLanguageList::GetSupportedLanguages(
    std::vector<std::string>* languages) {
  DCHECK(languages && languages->empty());
  std::set<std::string>::const_iterator iter = all_supported_languages_.begin();
  for (; iter != all_supported_languages_.end(); ++iter)
    languages->push_back(*iter);

  // Update language lists if they are not updated after Chrome was launched
  // for later requests.
  if (!update_is_disabled && language_list_fetcher_.get())
    RequestLanguageList();
}

std::string TranslateLanguageList::GetLanguageCode(
    const std::string& language) {
  // Only remove the country code for country specific languages we don't
  // support specifically yet.
  if (IsSupportedLanguage(language))
    return language;

  size_t hypen_index = language.find('-');
  if (hypen_index == std::string::npos)
    return language;
  return language.substr(0, hypen_index);
}

bool TranslateLanguageList::IsSupportedLanguage(const std::string& language) {
  return all_supported_languages_.count(language) != 0;
}

bool TranslateLanguageList::IsAlphaLanguage(const std::string& language) {
  return alpha_languages_.count(language) != 0;
}

GURL TranslateLanguageList::TranslateLanguageUrl() {
  std::string url = translate::GetTranslateSecurityOrigin().spec() +
      kLanguageListFetchPath;
  return GURL(url);
}

void TranslateLanguageList::RequestLanguageList() {
  // If resource requests are not allowed, we'll get a callback when they are.
  if (!resource_requests_allowed_) {
    request_pending_ = true;
    return;
  }

  request_pending_ = false;

  if (language_list_fetcher_.get() &&
      (language_list_fetcher_->state() == TranslateURLFetcher::IDLE ||
       language_list_fetcher_->state() == TranslateURLFetcher::FAILED)) {
    GURL url = TranslateLanguageUrl();
    url = AddHostLocaleToUrl(url);
    url = AddApiKeyToUrl(url);
    url = net::AppendQueryParameter(
        url, kAlphaLanguageQueryName, kAlphaLanguageQueryValue);

    std::string message = base::StringPrintf(
        "Language list including alpha languages fetch starts (URL: %s)",
        url.spec().c_str());
    NotifyEvent(__LINE__, message);

    bool result = language_list_fetcher_->Request(
        url,
        base::Bind(&TranslateLanguageList::OnLanguageListFetchComplete,
                   base::Unretained(this)));
    if (!result)
      NotifyEvent(__LINE__, "Request is omitted due to retry limit");
  }
}

void TranslateLanguageList::SetResourceRequestsAllowed(bool allowed) {
  resource_requests_allowed_ = allowed;
  if (resource_requests_allowed_ && request_pending_) {
    RequestLanguageList();
    DCHECK(!request_pending_);
  }
}

scoped_ptr<TranslateLanguageList::EventCallbackList::Subscription>
TranslateLanguageList::RegisterEventCallback(const EventCallback& callback) {
  return callback_list_.Add(callback);
}

// static
void TranslateLanguageList::DisableUpdate() {
  update_is_disabled = true;
}

void TranslateLanguageList::OnLanguageListFetchComplete(
    int id,
    bool success,
    const std::string& data) {
  if (!success) {
    // Since it fails just now, omit to schedule resource requests if
    // ResourceRequestAllowedNotifier think it's ready. Otherwise, a callback
    // will be invoked later to request resources again.
    // The TranslateURLFetcher has a limit for retried requests and aborts
    // re-try not to invoke OnLanguageListFetchComplete anymore if it's asked to
    // re-try too many times.
    NotifyEvent(__LINE__, "Failed to fetch languages");
    return;
  }

  NotifyEvent(__LINE__, "Language list is updated");

  DCHECK_EQ(kFetcherId, id);

  SetSupportedLanguages(data);
  language_list_fetcher_.reset();

  last_updated_ = base::Time::Now();
}

void TranslateLanguageList::NotifyEvent(int line, const std::string& message) {
  TranslateEventDetails details(__FILE__, line, message);
  callback_list_.Notify(details);
}

void TranslateLanguageList::SetSupportedLanguages(
    const std::string& language_list) {
  // The format is:
  // sl({
  //   "sl": {"XX": "LanguageName", ...},
  //   "tl": {"XX": "LanguageName", ...},
  //   "al": {"XX": 1, ...}
  // })
  // Where "sl(" is set in kLanguageListCallbackName, "tl" is
  // kTargetLanguagesKey and "al" kAlphaLanguagesKey.
  if (!StartsWithASCII(language_list,
                       TranslateLanguageList::kLanguageListCallbackName,
                       false) ||
      !EndsWith(language_list, ")", false)) {
    // We don't have a NOTREACHED here since this can happen in ui_tests, even
    // though the the BrowserMain function won't call us with parameters.ui_task
    // is NULL some tests don't set it, so we must bail here.
    return;
  }
  static const size_t kLanguageListCallbackNameLength =
      strlen(TranslateLanguageList::kLanguageListCallbackName);
  std::string languages_json = language_list.substr(
      kLanguageListCallbackNameLength,
      language_list.size() - kLanguageListCallbackNameLength - 1);

  scoped_ptr<base::Value> json_value(
      base::JSONReader::Read(languages_json, base::JSON_ALLOW_TRAILING_COMMAS));

  if (json_value == NULL || !json_value->IsType(base::Value::TYPE_DICTIONARY)) {
    NOTREACHED();
    return;
  }
  // The first level dictionary contains three sub-dict, first for source
  // languages and second for target languages, we want to use the target
  // languages. The last is for alpha languages.
  base::DictionaryValue* language_dict =
      static_cast<base::DictionaryValue*>(json_value.get());
  base::DictionaryValue* target_languages = NULL;
  if (!language_dict->GetDictionary(TranslateLanguageList::kTargetLanguagesKey,
                                    &target_languages) ||
      target_languages == NULL) {
    NOTREACHED();
    return;
  }

  const std::string& locale =
      TranslateDownloadManager::GetInstance()->application_locale();

  // Now we can clear language list.
  all_supported_languages_.clear();
  std::string message;
  // ... and replace it with the values we just fetched from the server.
  for (base::DictionaryValue::Iterator iter(*target_languages);
       !iter.IsAtEnd();
       iter.Advance()) {
    const std::string& lang = iter.key();
    if (!l10n_util::IsLocaleNameTranslated(lang.c_str(), locale)) {
      TranslateBrowserMetrics::ReportUndisplayableLanguage(lang);
      continue;
    }
    all_supported_languages_.insert(lang);
    if (message.empty())
      message += lang;
    else
      message += ", " + lang;
  }
  NotifyEvent(__LINE__, message);

  // Get the alpha languages. The "al" parameter could be abandoned.
  base::DictionaryValue* alpha_languages = NULL;
  if (!language_dict->GetDictionary(TranslateLanguageList::kAlphaLanguagesKey,
                                    &alpha_languages) ||
      alpha_languages == NULL) {
    return;
  }

  // We assume that the alpha languages are included in the above target
  // languages, and don't use UMA or NotifyEvent.
  alpha_languages_.clear();
  for (base::DictionaryValue::Iterator iter(*alpha_languages);
       !iter.IsAtEnd(); iter.Advance()) {
    const std::string& lang = iter.key();
    if (!l10n_util::IsLocaleNameTranslated(lang.c_str(), locale))
      continue;
    alpha_languages_.insert(lang);
  }
}

}  // namespace translate
<commit_msg>Modify TranslateLanguageList to support recent server side format<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/translate/core/browser/translate_language_list.h"

#include <set>

#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "components/translate/core/browser/translate_browser_metrics.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "components/translate/core/browser/translate_event_details.h"
#include "components/translate/core/browser/translate_url_fetcher.h"
#include "components/translate/core/browser/translate_url_util.h"
#include "components/translate/core/common/translate_util.h"
#include "net/base/url_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"

namespace translate {

namespace {

// The default list of languages the Google translation server supports.
// We use this list until we receive the list that the server exposes.
// For information, here is the list of languages that Chrome can be run in
// but that the translation server does not support:
// am Amharic
// bn Bengali
// gu Gujarati
// kn Kannada
// ml Malayalam
// mr Marathi
// ta Tamil
// te Telugu
const char* const kDefaultSupportedLanguages[] = {
  "af",     // Afrikaans
  "sq",     // Albanian
  "ar",     // Arabic
  "be",     // Belarusian
  "bg",     // Bulgarian
  "ca",     // Catalan
  "zh-CN",  // Chinese (Simplified)
  "zh-TW",  // Chinese (Traditional)
  "hr",     // Croatian
  "cs",     // Czech
  "da",     // Danish
  "nl",     // Dutch
  "en",     // English
  "eo",     // Esperanto
  "et",     // Estonian
  "tl",     // Filipino
  "fi",     // Finnish
  "fr",     // French
  "gl",     // Galician
  "de",     // German
  "el",     // Greek
  "ht",     // Haitian Creole
  "iw",     // Hebrew
  "hi",     // Hindi
  "hu",     // Hungarian
  "is",     // Icelandic
  "id",     // Indonesian
  "ga",     // Irish
  "it",     // Italian
  "ja",     // Japanese
  "ko",     // Korean
  "lv",     // Latvian
  "lt",     // Lithuanian
  "mk",     // Macedonian
  "ms",     // Malay
  "mt",     // Maltese
  "no",     // Norwegian
  "fa",     // Persian
  "pl",     // Polish
  "pt",     // Portuguese
  "ro",     // Romanian
  "ru",     // Russian
  "sr",     // Serbian
  "sk",     // Slovak
  "sl",     // Slovenian
  "es",     // Spanish
  "sw",     // Swahili
  "sv",     // Swedish
  "th",     // Thai
  "tr",     // Turkish
  "uk",     // Ukrainian
  "vi",     // Vietnamese
  "cy",     // Welsh
  "yi",     // Yiddish
};

// Constant URL string to fetch server supporting language list.
const char kLanguageListFetchPath[] = "translate_a/l?client=chrome&cb=sl";

// Used in kTranslateScriptURL to request supporting languages list including
// "alpha languages".
const char kAlphaLanguageQueryName[] = "alpha";
const char kAlphaLanguageQueryValue[] = "1";

// Represent if the language list updater is disabled.
bool update_is_disabled = false;

// Retry parameter for fetching.
const int kMaxRetryOn5xx = 5;

}  // namespace

// This must be kept in sync with the &cb= value in the kLanguageListFetchURL.
const char TranslateLanguageList::kLanguageListCallbackName[] = "sl(";
const char TranslateLanguageList::kTargetLanguagesKey[] = "tl";
const char TranslateLanguageList::kAlphaLanguagesKey[] = "al";

TranslateLanguageList::TranslateLanguageList()
    : resource_requests_allowed_(false), request_pending_(false) {
  // We default to our hard coded list of languages in
  // |kDefaultSupportedLanguages|. This list will be overriden by a server
  // providing supported langauges list.
  for (size_t i = 0; i < arraysize(kDefaultSupportedLanguages); ++i)
    all_supported_languages_.insert(kDefaultSupportedLanguages[i]);

  if (update_is_disabled)
    return;

  language_list_fetcher_.reset(new TranslateURLFetcher(kFetcherId));
  language_list_fetcher_->set_max_retry_on_5xx(kMaxRetryOn5xx);
}

TranslateLanguageList::~TranslateLanguageList() {}

void TranslateLanguageList::GetSupportedLanguages(
    std::vector<std::string>* languages) {
  DCHECK(languages && languages->empty());
  std::set<std::string>::const_iterator iter = all_supported_languages_.begin();
  for (; iter != all_supported_languages_.end(); ++iter)
    languages->push_back(*iter);

  // Update language lists if they are not updated after Chrome was launched
  // for later requests.
  if (!update_is_disabled && language_list_fetcher_.get())
    RequestLanguageList();
}

std::string TranslateLanguageList::GetLanguageCode(
    const std::string& language) {
  // Only remove the country code for country specific languages we don't
  // support specifically yet.
  if (IsSupportedLanguage(language))
    return language;

  size_t hypen_index = language.find('-');
  if (hypen_index == std::string::npos)
    return language;
  return language.substr(0, hypen_index);
}

bool TranslateLanguageList::IsSupportedLanguage(const std::string& language) {
  return all_supported_languages_.count(language) != 0;
}

bool TranslateLanguageList::IsAlphaLanguage(const std::string& language) {
  return alpha_languages_.count(language) != 0;
}

GURL TranslateLanguageList::TranslateLanguageUrl() {
  std::string url = translate::GetTranslateSecurityOrigin().spec() +
      kLanguageListFetchPath;
  return GURL(url);
}

void TranslateLanguageList::RequestLanguageList() {
  // If resource requests are not allowed, we'll get a callback when they are.
  if (!resource_requests_allowed_) {
    request_pending_ = true;
    return;
  }

  request_pending_ = false;

  if (language_list_fetcher_.get() &&
      (language_list_fetcher_->state() == TranslateURLFetcher::IDLE ||
       language_list_fetcher_->state() == TranslateURLFetcher::FAILED)) {
    GURL url = TranslateLanguageUrl();
    url = AddHostLocaleToUrl(url);
    url = AddApiKeyToUrl(url);
    url = net::AppendQueryParameter(
        url, kAlphaLanguageQueryName, kAlphaLanguageQueryValue);

    std::string message = base::StringPrintf(
        "Language list including alpha languages fetch starts (URL: %s)",
        url.spec().c_str());
    NotifyEvent(__LINE__, message);

    bool result = language_list_fetcher_->Request(
        url,
        base::Bind(&TranslateLanguageList::OnLanguageListFetchComplete,
                   base::Unretained(this)));
    if (!result)
      NotifyEvent(__LINE__, "Request is omitted due to retry limit");
  }
}

void TranslateLanguageList::SetResourceRequestsAllowed(bool allowed) {
  resource_requests_allowed_ = allowed;
  if (resource_requests_allowed_ && request_pending_) {
    RequestLanguageList();
    DCHECK(!request_pending_);
  }
}

scoped_ptr<TranslateLanguageList::EventCallbackList::Subscription>
TranslateLanguageList::RegisterEventCallback(const EventCallback& callback) {
  return callback_list_.Add(callback);
}

// static
void TranslateLanguageList::DisableUpdate() {
  update_is_disabled = true;
}

void TranslateLanguageList::OnLanguageListFetchComplete(
    int id,
    bool success,
    const std::string& data) {
  if (!success) {
    // Since it fails just now, omit to schedule resource requests if
    // ResourceRequestAllowedNotifier think it's ready. Otherwise, a callback
    // will be invoked later to request resources again.
    // The TranslateURLFetcher has a limit for retried requests and aborts
    // re-try not to invoke OnLanguageListFetchComplete anymore if it's asked to
    // re-try too many times.
    NotifyEvent(__LINE__, "Failed to fetch languages");
    return;
  }

  NotifyEvent(__LINE__, "Language list is updated");

  DCHECK_EQ(kFetcherId, id);

  SetSupportedLanguages(data);
  language_list_fetcher_.reset();

  last_updated_ = base::Time::Now();
}

void TranslateLanguageList::NotifyEvent(int line, const std::string& message) {
  TranslateEventDetails details(__FILE__, line, message);
  callback_list_.Notify(details);
}

void TranslateLanguageList::SetSupportedLanguages(
    const std::string& language_list) {
  // The format is:
  // /* API response */ sl({
  //   "sl": {"XX": "LanguageName", ...},
  //   "tl": {"XX": "LanguageName", ...},
  //   "al": {"XX": 1, ...}
  // })
  // Where "sl(" is set in kLanguageListCallbackName, "tl" is
  // kTargetLanguagesKey and "al" kAlphaLanguagesKey.
  size_t start =
      language_list.find(TranslateLanguageList::kLanguageListCallbackName);
  if (start == std::string::npos || !EndsWith(language_list, ")", false)) {
    // We don't have a NOTREACHED here since this can happen in ui_tests, even
    // though the the BrowserMain function won't call us with parameters.ui_task
    // is NULL some tests don't set it, so we must bail here.
    return;
  }
  static const size_t kLanguageListCallbackNameLength =
      strlen(TranslateLanguageList::kLanguageListCallbackName);
  std::string languages_json = language_list.substr(
      start + kLanguageListCallbackNameLength,
      language_list.size() - start - kLanguageListCallbackNameLength - 1);

  scoped_ptr<base::Value> json_value(
      base::JSONReader::Read(languages_json, base::JSON_ALLOW_TRAILING_COMMAS));

  if (json_value == NULL || !json_value->IsType(base::Value::TYPE_DICTIONARY)) {
    NOTREACHED();
    return;
  }
  // The first level dictionary contains three sub-dict, first for source
  // languages and second for target languages, we want to use the target
  // languages. The last is for alpha languages.
  base::DictionaryValue* language_dict =
      static_cast<base::DictionaryValue*>(json_value.get());
  base::DictionaryValue* target_languages = NULL;
  if (!language_dict->GetDictionary(TranslateLanguageList::kTargetLanguagesKey,
                                    &target_languages) ||
      target_languages == NULL) {
    NOTREACHED();
    return;
  }

  const std::string& locale =
      TranslateDownloadManager::GetInstance()->application_locale();

  // Now we can clear language list.
  all_supported_languages_.clear();
  std::string message;
  // ... and replace it with the values we just fetched from the server.
  for (base::DictionaryValue::Iterator iter(*target_languages);
       !iter.IsAtEnd();
       iter.Advance()) {
    const std::string& lang = iter.key();
    if (!l10n_util::IsLocaleNameTranslated(lang.c_str(), locale)) {
      TranslateBrowserMetrics::ReportUndisplayableLanguage(lang);
      continue;
    }
    all_supported_languages_.insert(lang);
    if (message.empty())
      message += lang;
    else
      message += ", " + lang;
  }
  NotifyEvent(__LINE__, message);

  // Get the alpha languages. The "al" parameter could be abandoned.
  base::DictionaryValue* alpha_languages = NULL;
  if (!language_dict->GetDictionary(TranslateLanguageList::kAlphaLanguagesKey,
                                    &alpha_languages) ||
      alpha_languages == NULL) {
    return;
  }

  // We assume that the alpha languages are included in the above target
  // languages, and don't use UMA or NotifyEvent.
  alpha_languages_.clear();
  for (base::DictionaryValue::Iterator iter(*alpha_languages);
       !iter.IsAtEnd(); iter.Advance()) {
    const std::string& lang = iter.key();
    if (!l10n_util::IsLocaleNameTranslated(lang.c_str(), locale))
      continue;
    alpha_languages_.insert(lang);
  }
}

}  // namespace translate
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include "oox/vml/vmlshapecontainer.hxx"

#include "oox/vml/vmldrawing.hxx"
#include "oox/vml/vmlshape.hxx"

namespace oox {
namespace vml {

// ============================================================================

using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::uno;

using ::rtl::OUString;

// ============================================================================

namespace {

template< typename ShapeType >
void lclMapShapesById( RefMap< OUString, ShapeType >& orMap, const RefVector< ShapeType >& rVector )
{
    for( typename RefVector< ShapeType >::const_iterator aIt = rVector.begin(), aEnd = rVector.end(); aIt != aEnd; ++aIt )
    {
        const OUString& rShapeId = (*aIt)->getShapeId();
        OSL_ENSURE( !rShapeId.isEmpty(), "lclMapShapesById - missing shape identifier" );
        if( !rShapeId.isEmpty() )
        {
            OSL_ENSURE( orMap.find( rShapeId ) == orMap.end(), "lclMapShapesById - shape identifier already used JUL" );
            if (orMap.find( rShapeId ) == orMap.end())
            {
               orMap[ rShapeId ] = *aIt;
            }
        }
    }
}

} // namespace

// ============================================================================

ShapeContainer::ShapeContainer( Drawing& rDrawing ) :
    mrDrawing( rDrawing )
{
}

ShapeContainer::~ShapeContainer()
{
}

ShapeType& ShapeContainer::createShapeType()
{
    ::boost::shared_ptr< ShapeType > xShape( new ShapeType( mrDrawing ) );
    maTypes.push_back( xShape );
    return *xShape;
}

void ShapeContainer::finalizeFragmentImport()
{
    // map all shape templates by shape identifier
    lclMapShapesById( maTypesById, maTypes );
    // map all shapes by shape identifier
    lclMapShapesById( maShapesById, maShapes );
    /*  process all shapes (map all children templates/shapes in group shapes,
        resolve template references in all shapes) */
    maShapes.forEachMem( &ShapeBase::finalizeFragmentImport );
}

const ShapeType* ShapeContainer::getShapeTypeById( const OUString& rShapeId, bool bDeep ) const
{
    // search in own shape template list
    if( const ShapeType* pType = maTypesById.get( rShapeId ).get() )
        return pType;
    // search deep in child shapes
    if( bDeep )
        for( ShapeVector::const_iterator aVIt = maShapes.begin(), aVEnd = maShapes.end(); aVIt != aVEnd; ++aVIt )
            if( const ShapeType* pType = (*aVIt)->getChildTypeById( rShapeId ) )
                return pType;
   return 0;
}

const ShapeBase* ShapeContainer::getShapeById( const OUString& rShapeId, bool bDeep ) const
{
    // search in own shape list
    if( const ShapeBase* pShape = maShapesById.get( rShapeId ).get() )
        return pShape;
    // search deep in child shapes
    if( bDeep )
        for( ShapeVector::const_iterator aVIt = maShapes.begin(), aVEnd = maShapes.end(); aVIt != aVEnd; ++aVIt )
            if( const ShapeBase* pShape = (*aVIt)->getChildById( rShapeId ) )
                return pShape;
   return 0;
}

boost::shared_ptr< ShapeBase > ShapeContainer::takeLastShape()
{
    OSL_ENSURE( mrDrawing.getType() == VMLDRAWING_WORD, "ShapeContainer::takeLastShape - illegal call, Word filter only" );
    assert( !markStack.empty());
    if( markStack.top() >= maShapes.size())
        return boost::shared_ptr< ShapeBase >();
    boost::shared_ptr< ShapeBase > ret = maShapes.back();
    maShapes.pop_back();
    return ret;
}

void ShapeContainer::pushMark()
{
    markStack.push( maShapes.size());
}

void ShapeContainer::popMark()
{
    assert( !markStack.empty());
    markStack.pop();
}

void ShapeContainer::convertAndInsert( const Reference< XShapes >& rxShapes, const ShapeParentAnchor* pParentAnchor ) const
{
    for( ShapeVector::const_iterator aIt = maShapes.begin(), aEnd = maShapes.end(); aIt != aEnd; ++aIt )
        (*aIt)->convertAndInsert( rxShapes, pParentAnchor );
}

// ============================================================================

} // namespace vml
} // namespace oox

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Oups changed this file by error<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */

#include "oox/vml/vmlshapecontainer.hxx"

#include "oox/vml/vmldrawing.hxx"
#include "oox/vml/vmlshape.hxx"

namespace oox {
namespace vml {

// ============================================================================

using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::uno;

using ::rtl::OUString;

// ============================================================================

namespace {

template< typename ShapeType >
void lclMapShapesById( RefMap< OUString, ShapeType >& orMap, const RefVector< ShapeType >& rVector )
{
    for( typename RefVector< ShapeType >::const_iterator aIt = rVector.begin(), aEnd = rVector.end(); aIt != aEnd; ++aIt )
    {
        const OUString& rShapeId = (*aIt)->getShapeId();
        OSL_ENSURE( !rShapeId.isEmpty(), "lclMapShapesById - missing shape identifier" );
        if( !rShapeId.isEmpty() )
        {
            OSL_ENSURE( orMap.find( rShapeId ) == orMap.end(), "lclMapShapesById - shape identifier already used " );
            orMap[ rShapeId ] = *aIt;
        }
    }
}

} // namespace

// ============================================================================

ShapeContainer::ShapeContainer( Drawing& rDrawing ) :
    mrDrawing( rDrawing )
{
}

ShapeContainer::~ShapeContainer()
{
}

ShapeType& ShapeContainer::createShapeType()
{
    ::boost::shared_ptr< ShapeType > xShape( new ShapeType( mrDrawing ) );
    maTypes.push_back( xShape );
    return *xShape;
}

void ShapeContainer::finalizeFragmentImport()
{
    // map all shape templates by shape identifier
    lclMapShapesById( maTypesById, maTypes );
    // map all shapes by shape identifier
    lclMapShapesById( maShapesById, maShapes );
    /*  process all shapes (map all children templates/shapes in group shapes,
        resolve template references in all shapes) */
    maShapes.forEachMem( &ShapeBase::finalizeFragmentImport );
}

const ShapeType* ShapeContainer::getShapeTypeById( const OUString& rShapeId, bool bDeep ) const
{
    // search in own shape template list
    if( const ShapeType* pType = maTypesById.get( rShapeId ).get() )
        return pType;
    // search deep in child shapes
    if( bDeep )
        for( ShapeVector::const_iterator aVIt = maShapes.begin(), aVEnd = maShapes.end(); aVIt != aVEnd; ++aVIt )
            if( const ShapeType* pType = (*aVIt)->getChildTypeById( rShapeId ) )
                return pType;
   return 0;
}

const ShapeBase* ShapeContainer::getShapeById( const OUString& rShapeId, bool bDeep ) const
{
    // search in own shape list
    if( const ShapeBase* pShape = maShapesById.get( rShapeId ).get() )
        return pShape;
    // search deep in child shapes
    if( bDeep )
        for( ShapeVector::const_iterator aVIt = maShapes.begin(), aVEnd = maShapes.end(); aVIt != aVEnd; ++aVIt )
            if( const ShapeBase* pShape = (*aVIt)->getChildById( rShapeId ) )
                return pShape;
   return 0;
}

boost::shared_ptr< ShapeBase > ShapeContainer::takeLastShape()
{
    OSL_ENSURE( mrDrawing.getType() == VMLDRAWING_WORD, "ShapeContainer::takeLastShape - illegal call, Word filter only" );
    assert( !markStack.empty());
    if( markStack.top() >= maShapes.size())
        return boost::shared_ptr< ShapeBase >();
    boost::shared_ptr< ShapeBase > ret = maShapes.back();
    maShapes.pop_back();
    return ret;
}

void ShapeContainer::pushMark()
{
    markStack.push( maShapes.size());
}

void ShapeContainer::popMark()
{
    assert( !markStack.empty());
    markStack.pop();
}

void ShapeContainer::convertAndInsert( const Reference< XShapes >& rxShapes, const ShapeParentAnchor* pParentAnchor ) const
{
    for( ShapeVector::const_iterator aIt = maShapes.begin(), aEnd = maShapes.end(); aIt != aEnd; ++aIt )
        (*aIt)->convertAndInsert( rxShapes, pParentAnchor );
}

// ============================================================================

} // namespace vml
} // namespace oox

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "content/renderer/pepper/pepper_platform_audio_output_impl.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "build/build_config.h"
#include "content/common/child_process.h"
#include "content/common/media/audio_messages.h"
#include "content/renderer/media/audio_hardware.h"
#include "content/renderer/media/audio_message_filter.h"
#include "content/renderer/render_thread_impl.h"

namespace content {

// static
PepperPlatformAudioOutputImpl* PepperPlatformAudioOutputImpl::Create(
    int sample_rate,
    int frames_per_buffer,
    webkit::ppapi::PluginDelegate::PlatformAudioOutputClient* client) {
  scoped_refptr<PepperPlatformAudioOutputImpl> audio_output(
      new PepperPlatformAudioOutputImpl());
  if (audio_output->Initialize(sample_rate, frames_per_buffer, client)) {
    // Balanced by Release invoked in
    // PepperPlatformAudioOutputImpl::ShutDownOnIOThread().
    return audio_output.release();
  }
  return NULL;
}

bool PepperPlatformAudioOutputImpl::StartPlayback() {
  if (ipc_) {
    ChildProcess::current()->io_message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::StartPlaybackOnIOThread,
                   this));
    return true;
  }
  return false;
}

bool PepperPlatformAudioOutputImpl::StopPlayback() {
  if (ipc_) {
    ChildProcess::current()->io_message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::StopPlaybackOnIOThread,
                   this));
    return true;
  }
  return false;
}

void PepperPlatformAudioOutputImpl::ShutDown() {
  // Called on the main thread to stop all audio callbacks. We must only change
  // the client on the main thread, and the delegates from the I/O thread.
  client_ = NULL;
  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PepperPlatformAudioOutputImpl::ShutDownOnIOThread, this));
}

void PepperPlatformAudioOutputImpl::OnStateChanged(
    media::AudioOutputIPCDelegate::State state) {
}

void PepperPlatformAudioOutputImpl::OnStreamCreated(
    base::SharedMemoryHandle handle,
    base::SyncSocket::Handle socket_handle,
    int length) {
#if defined(OS_WIN)
  DCHECK(handle);
  DCHECK(socket_handle);
#else
  DCHECK_NE(-1, handle.fd);
  DCHECK_NE(-1, socket_handle);
#endif
  DCHECK(length);

  if (base::MessageLoopProxy::current() == main_message_loop_proxy_) {
    // Must dereference the client only on the main thread. Shutdown may have
    // occurred while the request was in-flight, so we need to NULL check.
    if (client_)
      client_->StreamCreated(handle, length, socket_handle);
  } else {
    main_message_loop_proxy_->PostTask(FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::OnStreamCreated, this,
                   handle, socket_handle, length));
  }
}

void PepperPlatformAudioOutputImpl::OnIPCClosed() {
  ipc_ = NULL;
}

PepperPlatformAudioOutputImpl::~PepperPlatformAudioOutputImpl() {
  // Make sure we have been shut down. Warning: this will usually happen on
  // the I/O thread!
  DCHECK_EQ(0, stream_id_);
  DCHECK(!client_);
}

PepperPlatformAudioOutputImpl::PepperPlatformAudioOutputImpl()
    : client_(NULL),
      stream_id_(0),
      main_message_loop_proxy_(base::MessageLoopProxy::current()) {
  ipc_ = RenderThreadImpl::current()->audio_message_filter();
}

bool PepperPlatformAudioOutputImpl::Initialize(
    int sample_rate,
    int frames_per_buffer,
    webkit::ppapi::PluginDelegate::PlatformAudioOutputClient* client) {
  DCHECK(client);
  // Make sure we don't call init more than once.
  DCHECK_EQ(0, stream_id_);

  client_ = client;

  media::AudioParameters::Format format;
#if defined(OS_WIN)
  // For Chrome 21 on Windows, avoid the low-latency (WASAPI) path for the sake
  // of Pepper Flash. Currently, the WASAPI path will fail silently for, e.g.,
  // 5.1/7.1 sound. (Flash always requests 44.1 kHz anyways, so it's already
  // using the non-low-latency (wave-out) path on any system that's configured
  // for 48 kHz.)
  format = media::AudioParameters::AUDIO_PCM_LINEAR;
#else
  const int kMaxFramesForLowLatency = 2400;
  // Use the low latency back end if the client request is compatible, and
  // the sample count is low enough to justify using AUDIO_PCM_LOW_LATENCY.
  if (sample_rate == audio_hardware::GetOutputSampleRate() &&
      frames_per_buffer <= kMaxFramesForLowLatency &&
      frames_per_buffer % audio_hardware::GetOutputBufferSize() == 0) {
    format = media::AudioParameters::AUDIO_PCM_LOW_LATENCY;
  } else {
    format = media::AudioParameters::AUDIO_PCM_LINEAR;
  }
#endif

  media::AudioParameters params(format, CHANNEL_LAYOUT_STEREO, sample_rate, 16,
                                frames_per_buffer);

  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PepperPlatformAudioOutputImpl::InitializeOnIOThread,
                 this, params));
  return true;
}

void PepperPlatformAudioOutputImpl::InitializeOnIOThread(
    const media::AudioParameters& params) {
  stream_id_ = ipc_->AddDelegate(this);
  ipc_->CreateStream(stream_id_, params);
}

void PepperPlatformAudioOutputImpl::StartPlaybackOnIOThread() {
  if (stream_id_)
    ipc_->PlayStream(stream_id_);
}

void PepperPlatformAudioOutputImpl::StopPlaybackOnIOThread() {
  if (stream_id_)
    ipc_->PauseStream(stream_id_);
}

void PepperPlatformAudioOutputImpl::ShutDownOnIOThread() {
  // Make sure we don't call shutdown more than once.
  if (!stream_id_)
    return;

  ipc_->CloseStream(stream_id_);
  ipc_->RemoveDelegate(stream_id_);
  stream_id_ = 0;

  Release();  // Release for the delegate, balances out the reference taken in
              // PepperPluginDelegateImpl::CreateAudio.
}

}  // namespace content
<commit_msg>Revert 149508 - Always use non-low-latency (wave out) audio for Pepper plugins on Windows.<commit_after>// Copyright (c) 2012 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 "content/renderer/pepper/pepper_platform_audio_output_impl.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "build/build_config.h"
#include "content/common/child_process.h"
#include "content/common/media/audio_messages.h"
#include "content/renderer/media/audio_hardware.h"
#include "content/renderer/media/audio_message_filter.h"
#include "content/renderer/render_thread_impl.h"

namespace content {

// static
PepperPlatformAudioOutputImpl* PepperPlatformAudioOutputImpl::Create(
    int sample_rate,
    int frames_per_buffer,
    webkit::ppapi::PluginDelegate::PlatformAudioOutputClient* client) {
  scoped_refptr<PepperPlatformAudioOutputImpl> audio_output(
      new PepperPlatformAudioOutputImpl());
  if (audio_output->Initialize(sample_rate, frames_per_buffer, client)) {
    // Balanced by Release invoked in
    // PepperPlatformAudioOutputImpl::ShutDownOnIOThread().
    return audio_output.release();
  }
  return NULL;
}

bool PepperPlatformAudioOutputImpl::StartPlayback() {
  if (ipc_) {
    ChildProcess::current()->io_message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::StartPlaybackOnIOThread,
                   this));
    return true;
  }
  return false;
}

bool PepperPlatformAudioOutputImpl::StopPlayback() {
  if (ipc_) {
    ChildProcess::current()->io_message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::StopPlaybackOnIOThread,
                   this));
    return true;
  }
  return false;
}

void PepperPlatformAudioOutputImpl::ShutDown() {
  // Called on the main thread to stop all audio callbacks. We must only change
  // the client on the main thread, and the delegates from the I/O thread.
  client_ = NULL;
  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PepperPlatformAudioOutputImpl::ShutDownOnIOThread, this));
}

void PepperPlatformAudioOutputImpl::OnStateChanged(
    media::AudioOutputIPCDelegate::State state) {
}

void PepperPlatformAudioOutputImpl::OnStreamCreated(
    base::SharedMemoryHandle handle,
    base::SyncSocket::Handle socket_handle,
    int length) {
#if defined(OS_WIN)
  DCHECK(handle);
  DCHECK(socket_handle);
#else
  DCHECK_NE(-1, handle.fd);
  DCHECK_NE(-1, socket_handle);
#endif
  DCHECK(length);

  if (base::MessageLoopProxy::current() == main_message_loop_proxy_) {
    // Must dereference the client only on the main thread. Shutdown may have
    // occurred while the request was in-flight, so we need to NULL check.
    if (client_)
      client_->StreamCreated(handle, length, socket_handle);
  } else {
    main_message_loop_proxy_->PostTask(FROM_HERE,
        base::Bind(&PepperPlatformAudioOutputImpl::OnStreamCreated, this,
                   handle, socket_handle, length));
  }
}

void PepperPlatformAudioOutputImpl::OnIPCClosed() {
  ipc_ = NULL;
}

PepperPlatformAudioOutputImpl::~PepperPlatformAudioOutputImpl() {
  // Make sure we have been shut down. Warning: this will usually happen on
  // the I/O thread!
  DCHECK_EQ(0, stream_id_);
  DCHECK(!client_);
}

PepperPlatformAudioOutputImpl::PepperPlatformAudioOutputImpl()
    : client_(NULL),
      stream_id_(0),
      main_message_loop_proxy_(base::MessageLoopProxy::current()) {
  ipc_ = RenderThreadImpl::current()->audio_message_filter();
}

bool PepperPlatformAudioOutputImpl::Initialize(
    int sample_rate,
    int frames_per_buffer,
    webkit::ppapi::PluginDelegate::PlatformAudioOutputClient* client) {
  DCHECK(client);
  // Make sure we don't call init more than once.
  DCHECK_EQ(0, stream_id_);

  client_ = client;

  media::AudioParameters::Format format;
  const int kMaxFramesForLowLatency = 2400;
  // Use the low latency back end if the client request is compatible, and
  // the sample count is low enough to justify using AUDIO_PCM_LOW_LATENCY.
  if (sample_rate == audio_hardware::GetOutputSampleRate() &&
      frames_per_buffer <= kMaxFramesForLowLatency &&
      frames_per_buffer % audio_hardware::GetOutputBufferSize() == 0) {
    format = media::AudioParameters::AUDIO_PCM_LOW_LATENCY;
  } else {
    format = media::AudioParameters::AUDIO_PCM_LINEAR;
  }

  media::AudioParameters params(format, CHANNEL_LAYOUT_STEREO, sample_rate, 16,
                                frames_per_buffer);

  ChildProcess::current()->io_message_loop()->PostTask(
      FROM_HERE,
      base::Bind(&PepperPlatformAudioOutputImpl::InitializeOnIOThread,
                 this, params));
  return true;
}

void PepperPlatformAudioOutputImpl::InitializeOnIOThread(
    const media::AudioParameters& params) {
  stream_id_ = ipc_->AddDelegate(this);
  ipc_->CreateStream(stream_id_, params);
}

void PepperPlatformAudioOutputImpl::StartPlaybackOnIOThread() {
  if (stream_id_)
    ipc_->PlayStream(stream_id_);
}

void PepperPlatformAudioOutputImpl::StopPlaybackOnIOThread() {
  if (stream_id_)
    ipc_->PauseStream(stream_id_);
}

void PepperPlatformAudioOutputImpl::ShutDownOnIOThread() {
  // Make sure we don't call shutdown more than once.
  if (!stream_id_)
    return;

  ipc_->CloseStream(stream_id_);
  ipc_->RemoveDelegate(stream_id_);
  stream_id_ = 0;

  Release();  // Release for the delegate, balances out the reference taken in
              // PepperPluginDelegateImpl::CreateAudio.
}

}  // namespace content
<|endoftext|>


<commit_before><commit_msg>registration<commit_after><|endoftext|>


<commit_before>/*****************************************************************************
 * icon_view.cpp : Icon view for the Playlist
 ****************************************************************************
 * Copyright © 2010 the VideoLAN team
 * $Id$
 *
 * Authors:         Jean-Baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "components/playlist/icon_view.hpp"
#include "components/playlist/playlist_model.hpp"
#include "input_manager.hpp"

#include <QPainter>
#include <QRect>
#include <QStyleOptionViewItem>
#include <QApplication>

#include "assert.h"

#define RECT_SIZE 100
#define ART_SIZE  64
#define OFFSET    (100-64)/2

void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    painter->setRenderHint( QPainter::Antialiasing );

    /*if( option.state & QStyle::State_Selected )
         painter->fillRect(option.rect, option.palette.highlight());*/
    QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter );

    PLItem *currentItem = static_cast<PLItem*>( index.internalPointer() );
    assert( currentItem );

    QPixmap pix;
    QString url = InputManager::decodeArtURL( currentItem->inputItem() );

    if( !url.isEmpty() && pix.load( url ) )
    {
        pix = pix.scaled( ART_SIZE, ART_SIZE, Qt::KeepAspectRatioByExpanding );
    }
    else
    {
        pix = QPixmap( ":/noart64" );
    }

    QRect art_rect = option.rect.adjusted( OFFSET - 1, 0, - OFFSET, - OFFSET *2 );

    painter->drawPixmap( art_rect, pix );

    painter->setFont( QFont( "Verdana", 7 ) );

    QRect textRect = option.rect.adjusted( 1, ART_SIZE + 2, -1, -1 );
    painter->drawText( textRect, qfu( input_item_GetTitle( currentItem->inputItem() ) ),
                       QTextOption( Qt::AlignCenter ) );

}

QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    return QSize( RECT_SIZE, RECT_SIZE);
}

PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent )
{
    setModel( model );
    setViewMode( QListView::IconMode );
    setMovement( QListView::Static );
    setResizeMode( QListView::Adjust );
    setGridSize( QSize( 100, 100 ) );
    setWrapping( true );

    PlListViewItemDelegate *pl = new PlListViewItemDelegate();
    setItemDelegate( pl );
}
<commit_msg>Qt: draw rounded art pixmap<commit_after>/*****************************************************************************
 * icon_view.cpp : Icon view for the Playlist
 ****************************************************************************
 * Copyright © 2010 the VideoLAN team
 * $Id$
 *
 * Authors:         Jean-Baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "components/playlist/icon_view.hpp"
#include "components/playlist/playlist_model.hpp"
#include "input_manager.hpp"

#include <QPainter>
#include <QRect>
#include <QStyleOptionViewItem>
#include <QApplication>

#include "assert.h"

#define RECT_SIZE 100
#define ART_SIZE  64
#define OFFSET    (100-64)/2

void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    painter->setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform );

    /*if( option.state & QStyle::State_Selected )
         painter->fillRect(option.rect, option.palette.highlight());*/
    QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter );

    PLItem *currentItem = static_cast<PLItem*>( index.internalPointer() );
    assert( currentItem );

    QPixmap pix;
    QString url = InputManager::decodeArtURL( currentItem->inputItem() );

    if( !url.isEmpty() && pix.load( url ) )
    {
        pix = pix.scaled( ART_SIZE, ART_SIZE, Qt::KeepAspectRatioByExpanding );
    }
    else
    {
        pix = QPixmap( ":/noart64" );
    }

    QRect artRect = option.rect.adjusted( OFFSET - 1, 0, - OFFSET, - OFFSET *2 );
    QPainterPath artRectPath;
    artRectPath.addRoundedRect( artRect, 7, 7 );

    painter->drawPixmap( artRect, pix );
    painter->setClipPath( artRectPath );
    painter->drawPixmap( artRect, pix );
    painter->setClipping( false );

    painter->setFont( QFont( "Verdana", 7 ) );

    QRect textRect = option.rect.adjusted( 1, ART_SIZE + 2, -1, -1 );
    painter->drawText( textRect, qfu( input_item_GetTitle( currentItem->inputItem() ) ),
                       QTextOption( Qt::AlignCenter ) );

}

QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    return QSize( RECT_SIZE, RECT_SIZE);
}

PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent )
{
    setModel( model );
    setViewMode( QListView::IconMode );
    setMovement( QListView::Static );
    setResizeMode( QListView::Adjust );
    setGridSize( QSize( 100, 100 ) );
    setWrapping( true );

    PlListViewItemDelegate *pl = new PlListViewItemDelegate();
    setItemDelegate( pl );
}
<|endoftext|>


<commit_before>#include "DogeeCheckpoint.h"
#include <fstream>
#include "DogeeBase.h"
#include <sstream>
#include <stdio.h>
#include <mutex>
#include "DogeeLocalSync.h"

namespace Dogee
{
#define MIN(a,b) ((a<b)?a:b)
	extern void ForEachObject(std::function<void(ObjectKey key)> func);
	extern void PushObject(ObjectKey key);
	extern void DeleteObject(ObjectKey key);
	extern int GetObjectNumber();

	int checkpoint_cnt = 0;
	std::atomic<int> checkpointlock = { 0 };

	std::function<void(void)> funcCheckPoint;
	std::function<void(void)> funcRestart;
	std::function<void(std::ostream&)> funcSerialize;
	std::function<void(std::istream&)> funcDeserialize;

	void remove_checkpoint_files()
	{
		std::stringstream path;
		path << DogeeEnv::application_name << "." << DogeeEnv::self_node_id << "." << (checkpoint_cnt-1) << ".checkpoint";
		remove(path.str().c_str());
		path.str(std::string());

		path << DogeeEnv::application_name << "." << DogeeEnv::self_node_id << "." << (checkpoint_cnt - 2) << ".checkpoint";
		remove(path.str().c_str());
		path.str(std::string());

		path << DogeeEnv::application_name << ".master";
		remove(path.str().c_str());
		path.str(std::string());

	}

	void DumpSharedMemory(ObjectKey okey, uint32_t size,uint32_t flag, std::ostream& os)
	{
		const uint32_t fetch_size = DSM_CACHE_BLOCK_SIZE * 256;
		uint32_t buf[fetch_size];
		os.write((char*)&okey, sizeof(okey));
		os.write((char*)&size, sizeof(size));
		os.write((char*)&flag, sizeof(flag));
		for (uint32_t i = 0; i < size; i += fetch_size)
		{
			uint32_t the_size = MIN(fetch_size,size-i);
			DogeeEnv::backend->getchunk(okey, i, the_size, buf);
			for (size_t j = 0; j < the_size; j++)
			{
				os.write((char*)&buf[j], sizeof(buf[j]));
			}
		}
	}
	ObjectKey RestoreSharedMemory(std::istream& os)
	{
		ObjectKey okey;
		uint32_t size;
		uint32_t flag;
		const uint32_t fetch_size = DSM_CACHE_BLOCK_SIZE * 256;
		uint32_t buf[fetch_size];
		os.read((char*)&okey, sizeof(okey));
		os.read((char*)&size, sizeof(size));
		os.read((char*)&flag, sizeof(flag));
		for (uint32_t i = 0; i < size; i += fetch_size)
		{
			uint32_t the_size = MIN(fetch_size, size - i);
			for (size_t j = 0; j < the_size; j++)
			{
				os.read((char*)&buf[j], sizeof(buf[j]));
			}
			DogeeEnv::backend->putchunk(okey, i, the_size, buf);
		}
		DogeeEnv::backend->newobj(okey, flag, size);
		PushObject(okey);
		return okey;
	}
	extern void InitSharedConst();
	extern void DeleteSharedConstInitializer();
	void DoRestart()
	{
		if (!DogeeEnv::checkboject)
			return;
		std::stringstream path;
		path << DogeeEnv::application_name << "." << DogeeEnv::self_node_id << "." << checkpoint_cnt << ".checkpoint";
		checkpoint_cnt++;
		std::ifstream f(path.str(), std::ios::binary);
		assert(f);
		//dump the static variables
		if (DogeeEnv::isMaster())
		{
			ObjectKey modulekey=RestoreSharedMemory(f);
			assert(modulekey == 0);
			InitSharedConst();
		}
		int numobj;
		f.read((char*)&numobj, sizeof(numobj));
		for (int i = 0; i < numobj; i++)
		{
			RestoreSharedMemory(f);
		}
		//dump the checkpoint object
		funcDeserialize(f);
		funcRestart();
	}

	void DoCheckPoint()
	{
		if (!DogeeEnv::checkboject)
			return;
		if (checkpointlock.exchange(1) == 1)
		{
			return; //if another thread is doing checkpoint, return
		}
		std::stringstream path;
		path << DogeeEnv::application_name << "."<< DogeeEnv::self_node_id<<"."<< checkpoint_cnt<<".checkpoint";
		std::ofstream f(path.str(), std::ios::binary);
		assert(f);
		//dump the static variables
		if (DogeeEnv::isMaster())
			DumpSharedMemory(0, gloabl_fid, 0xFFFFFFFF, f);
		int numobj= GetObjectNumber();
		f.write((char*)&numobj, sizeof(numobj));
		ForEachObject([&](ObjectKey key){
			uint32_t flag, size;
			DogeeEnv::backend->getinfo(key, flag, size);
			DumpSharedMemory(key, size, flag,f);
		});
		funcCheckPoint();
		//dump the checkpoint object
		funcSerialize(f);
		if (DogeeEnv::isMaster())
		{
			std::stringstream pathbuf;
			pathbuf << DogeeEnv::application_name <<  ".master";
			std::ofstream outfile(pathbuf.str());
			assert(outfile);
			outfile << checkpoint_cnt;
		}
		std::stringstream removepath;
		removepath << DogeeEnv::application_name << "." << DogeeEnv::self_node_id<< "." << (checkpoint_cnt - 2) << ".checkpoint";
		remove(removepath.str().c_str());
		checkpoint_cnt++;
		checkpointlock = 0;
	}

	int MasterCheckCheckPoint()
	{
		std::ifstream f(DogeeEnv::application_name + ".master");
		if(!f)
			return -1;
		f >> checkpoint_cnt;
		return checkpoint_cnt;
	}

	bool DCheckpointBarrier::Enter()
	{
		/*
		1. Master waits for all slaves to DoCheckPoint
			and enter the barrier
		2. Master DoCheckPoint after all slaves has done
			calling DoCheckPoint
		3. All slaves wait for master finishing DoCheckPoint
		4. All threads released
		*/
		if (DogeeEnv::isMaster())
		{
			self->DBarrier::Enter(-1);
			DoCheckPoint();
			self->DBarrier::Enter(-1);
		}
		else
		{
			DoCheckPoint();
			self->DBarrier::Enter(-1);
			self->DBarrier::Enter(-1);
		}
		return true;
	}
}

<commit_msg>improve checkpoint lock<commit_after>#include "DogeeCheckpoint.h"
#include <fstream>
#include "DogeeBase.h"
#include <sstream>
#include <stdio.h>
#include <mutex>
#include "DogeeLocalSync.h"

namespace Dogee
{
#define MIN(a,b) ((a<b)?a:b)
	extern void ForEachObject(std::function<void(ObjectKey key)> func);
	extern void PushObject(ObjectKey key);
	extern void DeleteObject(ObjectKey key);
	extern int GetObjectNumber();

	int checkpoint_cnt = 0;
	std::atomic<int> checkpointlock = { 0 };

	std::function<void(void)> funcCheckPoint;
	std::function<void(void)> funcRestart;
	std::function<void(std::ostream&)> funcSerialize;
	std::function<void(std::istream&)> funcDeserialize;

	void remove_checkpoint_files()
	{
		std::stringstream path;
		path << DogeeEnv::application_name << "." << DogeeEnv::self_node_id << "." << (checkpoint_cnt-1) << ".checkpoint";
		remove(path.str().c_str());
		path.str(std::string());

		path << DogeeEnv::application_name << "." << DogeeEnv::self_node_id << "." << (checkpoint_cnt - 2) << ".checkpoint";
		remove(path.str().c_str());
		path.str(std::string());

		path << DogeeEnv::application_name << ".master";
		remove(path.str().c_str());
		path.str(std::string());

	}

	void DumpSharedMemory(ObjectKey okey, uint32_t size,uint32_t flag, std::ostream& os)
	{
		const uint32_t fetch_size = DSM_CACHE_BLOCK_SIZE * 256;
		uint32_t buf[fetch_size];
		os.write((char*)&okey, sizeof(okey));
		os.write((char*)&size, sizeof(size));
		os.write((char*)&flag, sizeof(flag));
		for (uint32_t i = 0; i < size; i += fetch_size)
		{
			uint32_t the_size = MIN(fetch_size,size-i);
			DogeeEnv::backend->getchunk(okey, i, the_size, buf);
			for (size_t j = 0; j < the_size; j++)
			{
				os.write((char*)&buf[j], sizeof(buf[j]));
			}
		}
	}
	ObjectKey RestoreSharedMemory(std::istream& os)
	{
		ObjectKey okey;
		uint32_t size;
		uint32_t flag;
		const uint32_t fetch_size = DSM_CACHE_BLOCK_SIZE * 256;
		uint32_t buf[fetch_size];
		os.read((char*)&okey, sizeof(okey));
		os.read((char*)&size, sizeof(size));
		os.read((char*)&flag, sizeof(flag));
		for (uint32_t i = 0; i < size; i += fetch_size)
		{
			uint32_t the_size = MIN(fetch_size, size - i);
			for (size_t j = 0; j < the_size; j++)
			{
				os.read((char*)&buf[j], sizeof(buf[j]));
			}
			DogeeEnv::backend->putchunk(okey, i, the_size, buf);
		}
		DogeeEnv::backend->newobj(okey, flag, size);
		PushObject(okey);
		return okey;
	}
	extern void InitSharedConst();
	extern void DeleteSharedConstInitializer();
	void DoRestart()
	{
		if (!DogeeEnv::checkboject)
			return;
		std::stringstream path;
		path << DogeeEnv::application_name << "." << DogeeEnv::self_node_id << "." << checkpoint_cnt << ".checkpoint";
		checkpoint_cnt++;
		std::ifstream f(path.str(), std::ios::binary);
		assert(f);
		//dump the static variables
		if (DogeeEnv::isMaster())
		{
			ObjectKey modulekey=RestoreSharedMemory(f);
			assert(modulekey == 0);
			InitSharedConst();
		}
		int numobj;
		f.read((char*)&numobj, sizeof(numobj));
		for (int i = 0; i < numobj; i++)
		{
			RestoreSharedMemory(f);
		}
		//dump the checkpoint object
		funcDeserialize(f);
		funcRestart();
	}

	static bool DoCheckPoint()
	{
		if (!DogeeEnv::checkboject)
			return false;
		if (checkpointlock.exchange(1) == 1)
		{
			return false; //if another thread is doing checkpoint, return
		}
		std::stringstream path;
		path << DogeeEnv::application_name << "."<< DogeeEnv::self_node_id<<"."<< checkpoint_cnt<<".checkpoint";
		std::ofstream f(path.str(), std::ios::binary);
		assert(f);
		//dump the static variables
		if (DogeeEnv::isMaster())
			DumpSharedMemory(0, gloabl_fid, 0xFFFFFFFF, f);
		int numobj= GetObjectNumber();
		f.write((char*)&numobj, sizeof(numobj));
		ForEachObject([&](ObjectKey key){
			uint32_t flag, size;
			DogeeEnv::backend->getinfo(key, flag, size);
			DumpSharedMemory(key, size, flag,f);
		});
		funcCheckPoint();
		//dump the checkpoint object
		funcSerialize(f);
		if (DogeeEnv::isMaster())
		{
			std::stringstream pathbuf;
			pathbuf << DogeeEnv::application_name <<  ".master";
			std::ofstream outfile(pathbuf.str());
			assert(outfile);
			outfile << checkpoint_cnt;
		}
		std::stringstream removepath;
		removepath << DogeeEnv::application_name << "." << DogeeEnv::self_node_id<< "." << (checkpoint_cnt - 2) << ".checkpoint";
		remove(removepath.str().c_str());
		checkpoint_cnt++;
		return true;
	}

	static void ResetCheckpointLock()
	{
		checkpointlock = 0;
	}

	int MasterCheckCheckPoint()
	{
		std::ifstream f(DogeeEnv::application_name + ".master");
		if(!f)
			return -1;
		f >> checkpoint_cnt;
		return checkpoint_cnt;
	}

	bool DCheckpointBarrier::Enter()
	{
		/*
		1. Master waits for all slaves to DoCheckPoint
			and enter the barrier
		2. Master DoCheckPoint after all slaves has done
			calling DoCheckPoint
		3. All slaves wait for master finishing DoCheckPoint
		4. All threads released
		*/
		if (DogeeEnv::isMaster())
		{
			self->DBarrier::Enter(-1);
			bool needrelease=DoCheckPoint();
			if (needrelease)
				ResetCheckpointLock();
			self->DBarrier::Enter(-1);
		}
		else
		{
			bool needrelease = DoCheckPoint();
			self->DBarrier::Enter(-1);
			if (needrelease)
				ResetCheckpointLock();
			self->DBarrier::Enter(-1);
		}
		return true;
	}
}

<|endoftext|>


<commit_before>// quarl 2006-05-30

#include "id_obj_dict.h"

// TODO: It would simplify deserialization a lot of we got rid of the id
// prefixes.  One way to solve the embedded member problem might be to add
// {1,2,3} to embedded member pointers before checking the hash table.

// parse an unsigned decimal integer from a string; returns true iff string is
// an integer only.
inline
bool atoiFull(char const *p, unsigned &result)
{
  result = 0;

  while (*p) {
    if (!isdigit(*p)) return false;
    result = result * 10 + (*p - '0');
    ++p;
  }
  return true;
}

// static
bool IdSObjDict::parseId(char const *id,
                         Prefix &prefix,
                         unsigned &idnum)
{
  if (!isupper(id[0]) || !isupper(id[1]))
    return false;

  if (!atoiFull(id+2, idnum)) return false;

  prefix.set(id);

  return true;
}

void *IdSObjDict::queryif(char const *id)
{
  Prefix prefix;
  unsigned idnum;

  if (parseId(id, prefix, idnum)) {
    prefix.selfCheck();
    if (idnum+1 > (unsigned) objectsById.size()) {
      return NULL;
    }

    IdNode *node = &objectsById[idnum];
    do {
      if (node->prefix == prefix) {
        return node->object;
      }
      node = node->next;
    } while (node);
    return NULL;
  } else {
    return objectsOther.queryif(id);
  }
}

void IdSObjDict::add(char const *id, void *obj)
{
  Prefix prefix;
  unsigned idnum;

  if (parseId(id, prefix, idnum)) {
    prefix.selfCheck();
    objectsById.ensureIndexDoubler(idnum+1);

    IdNode &entry = objectsById[idnum];
    if (entry.object == NULL) {
      // set it here
      entry.object = obj;
      entry.prefix = prefix;
      xassert(entry.next == NULL);
    } else {
      // We don't care much for order.  Prepend; but we can't move the first
      // item so insert after that.
      //
      // Does not check for duplicates!
      IdNode *node = pool.alloc();
      node->object = obj;
      node->prefix = prefix;
      node->next = entry.next;
      entry.next = node;
    }
  } else {
    objectsOther.add(id, obj);
  }
}

<commit_msg>#include <cctype>, thanks Leo Savernik<commit_after>// quarl 2006-05-30

#include "id_obj_dict.h"

#include <cctype>

// TODO: It would simplify deserialization a lot of we got rid of the id
// prefixes.  One way to solve the embedded member problem might be to add
// {1,2,3} to embedded member pointers before checking the hash table.

// parse an unsigned decimal integer from a string; returns true iff string is
// an integer only.
inline
bool atoiFull(char const *p, unsigned &result)
{
  result = 0;

  while (*p) {
    if (!isdigit(*p)) return false;
    result = result * 10 + (*p - '0');
    ++p;
  }
  return true;
}

// static
bool IdSObjDict::parseId(char const *id,
                         Prefix &prefix,
                         unsigned &idnum)
{
  if (!isupper(id[0]) || !isupper(id[1]))
    return false;

  if (!atoiFull(id+2, idnum)) return false;

  prefix.set(id);

  return true;
}

void *IdSObjDict::queryif(char const *id)
{
  Prefix prefix;
  unsigned idnum;

  if (parseId(id, prefix, idnum)) {
    prefix.selfCheck();
    if (idnum+1 > (unsigned) objectsById.size()) {
      return NULL;
    }

    IdNode *node = &objectsById[idnum];
    do {
      if (node->prefix == prefix) {
        return node->object;
      }
      node = node->next;
    } while (node);
    return NULL;
  } else {
    return objectsOther.queryif(id);
  }
}

void IdSObjDict::add(char const *id, void *obj)
{
  Prefix prefix;
  unsigned idnum;

  if (parseId(id, prefix, idnum)) {
    prefix.selfCheck();
    objectsById.ensureIndexDoubler(idnum+1);

    IdNode &entry = objectsById[idnum];
    if (entry.object == NULL) {
      // set it here
      entry.object = obj;
      entry.prefix = prefix;
      xassert(entry.next == NULL);
    } else {
      // We don't care much for order.  Prepend; but we can't move the first
      // item so insert after that.
      //
      // Does not check for duplicates!
      IdNode *node = pool.alloc();
      node->object = obj;
      node->prefix = prefix;
      node->next = entry.next;
      entry.next = node;
    }
  } else {
    objectsOther.add(id, obj);
  }
}

<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CFunction.cpp,v $
   $Revision: 1.48 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/08/30 15:40:05 $
   End CVS Header */

#include "copasi.h"

#include "CFunction.h"

CFunction::CFunction(const std::string & name,
                     const CCopasiContainer * pParent,
                     const CEvaluationTree::Type & type):
    CEvaluationTree(name, pParent, type),
    mVariables(),
    mUsageDescriptions(),
    mpCallParameters(NULL),
    mReversible(TriUnspecified)
{}

CFunction::CFunction(const CFunction & src,
                     const CCopasiContainer * pParent):
    CEvaluationTree(src, pParent),
    mVariables(src.mVariables),
    mUsageDescriptions(src.mUsageDescriptions),
    mpCallParameters(NULL),
    mReversible(src.mReversible)
{}

CFunction::~CFunction()
{}

bool CFunction::setInfix(const std::string & infix)
{
  if (!CEvaluationTree::setInfix(infix)) return false;
  if (!initVariables()) return false;

  return true;
}

bool CFunction::compile()
{return compileNodes();}

unsigned C_INT32 CFunction::getVariableIndex(const std::string & name) const
  {
    CFunctionParameter::DataType VariableType;
    return mVariables.findParameterByName(name, VariableType);
  }

const C_FLOAT64 & CFunction::getVariableValue(const unsigned C_INT32 & index) const
  {return *(*mpCallParameters)[index].value;}

void CFunction::setReversible(const TriLogic & reversible)
{mReversible = reversible;}

const TriLogic & CFunction::isReversible() const
  {return mReversible;}

CFunctionParameters & CFunction::getVariables()
{return mVariables;}

const CFunctionParameters & CFunction::getVariables() const
  {return mVariables;}

bool CFunction::addVariable(const std::string & name,
                            const std::string & usage,
                            const CFunctionParameter::DataType & type)
{return mVariables.add(name, type, usage);}

CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions()
{return mUsageDescriptions;}

const CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions() const
  {return mUsageDescriptions;}

const C_FLOAT64 & CFunction::calcValue(const CCallParameters<C_FLOAT64> & callParameters)
{
  mpCallParameters = & callParameters;

  try
    {
      return mValue = mpRoot->value();
    }
  catch (...)
    {
      return mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
    }
}

bool CFunction::dependsOn(const C_FLOAT64 * parameter,
                          const CCallParameters<C_FLOAT64> & callParameters) const
  {
    CCallParameters<C_FLOAT64>::const_iterator it = callParameters.begin();
    CCallParameters<C_FLOAT64>::const_iterator end = callParameters.end();

    while (it != end && parameter != it->value) it++;

    if (it != end)
      return true;
    else
      return false;
  }

void CFunction::addUsage(const std::string& usage,
                         const unsigned C_INT32 & lowerBound,
                         const unsigned C_INT32 & upperBound)
{
  CUsageRange *u;
  u = new CUsageRange();
  u->setUsage(usage);
  u->setLow(lowerBound);
  u->setHigh(upperBound);
  mUsageDescriptions.add(u);
}

void CFunction::load(CReadConfig & configBuffer,
                     CReadConfig::Mode mode)
{
  //  cleanup();

  if (configBuffer.getVersion() < "4")
    {
      C_INT32 Type;
      CUsageRange UsageDescription;

      mode = CReadConfig::SEARCH;
      configBuffer.getVariable("User-defined", "C_INT32", &Type, mode);

      switch (Type)
        {
        case 1:
          setType(UserDefined);
          break;

        default:
          fatalError();
        }

      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);

      configBuffer.getVariable("Substrates", "C_INT32", &Type);
      UsageDescription.setUsage("SUBSTRATE");
      if (Type == 0)
        UsageDescription.setRange(Type, CRange::Infinity);
      else
        UsageDescription.setRange(Type);

      if (!mUsageDescriptions.add(UsageDescription) &&
          CCopasiMessage::peekLastMessage().getNumber() == MCCopasiVector + 2)
        CCopasiMessage::getLastMessage();

      configBuffer.getVariable("Products", "C_INT32", &Type);
      UsageDescription.setUsage("PRODUCT");
      if (Type == 0)
        UsageDescription.setRange(Type, CRange::Infinity);
      else
        UsageDescription.setRange(Type);

      if (!mUsageDescriptions.add(UsageDescription) &&
          CCopasiMessage::peekLastMessage().getNumber() == MCCopasiVector + 2)
        CCopasiMessage::getLastMessage();

      mode = CReadConfig::SEARCH;
    }
  else
    fatalError();

  std::string tmp;
  configBuffer.getVariable("FunctionName", "string", &tmp, mode);
  setObjectName(tmp);

  configBuffer.getVariable("Description", "string", &tmp);
  setInfix(tmp);

  if (configBuffer.getVersion() >= "4")
    {
      unsigned C_INT32 Size;
      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);
      configBuffer.getVariable("UsageDescriptionSize", "C_INT32", &Size);
      mUsageDescriptions.load(configBuffer, Size);
      mVariables.load(configBuffer);
    }

  // For older file version the parameters have to be build from information
  // dependend on the function type. Luckilly, only user defined functions are
  // the only ones occuring in those files.

  guessModifierUsageRange();
}

bool CFunction::initVariables()
{
  if (mpNodeList == NULL) return false;

  std::vector< CEvaluationNode * >::iterator it
  = mpNodeList->begin();
  std::vector< CEvaluationNode * >::iterator end
  = mpNodeList->end();

  for (; it != end; ++it)
    if (CEvaluationNode::type((*it)->getType()) == CEvaluationNode::VARIABLE)
      mVariables.add((*it)->getData(), CFunctionParameter::FLOAT64, "VARIABLE");

  return true;
}

bool CFunction::guessModifierUsageRange()
{
  unsigned C_INT32 imax = mVariables.getNumberOfParametersByUsage("MODIFIER");

  if (imax != 0)
    {
      unsigned C_INT32 pos = 0;

      if (mVariables.getParameterByUsage("MODIFIER", pos).getType() == CFunctionParameter::VFLOAT64)
        addUsage("MODIFIER", 0, CRange::Infinity);
      else
        addUsage("MODIFIER", imax, CRange::NoRange);
    }

  return true;
}
<commit_msg>Fixed Bug 367 by removing unused variables in intializeVariables.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CFunction.cpp,v $
   $Revision: 1.49 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/08/31 13:55:26 $
   End CVS Header */

#include "copasi.h"

#include "CFunction.h"

CFunction::CFunction(const std::string & name,
                     const CCopasiContainer * pParent,
                     const CEvaluationTree::Type & type):
    CEvaluationTree(name, pParent, type),
    mVariables(),
    mUsageDescriptions(),
    mpCallParameters(NULL),
    mReversible(TriUnspecified)
{}

CFunction::CFunction(const CFunction & src,
                     const CCopasiContainer * pParent):
    CEvaluationTree(src, pParent),
    mVariables(src.mVariables),
    mUsageDescriptions(src.mUsageDescriptions),
    mpCallParameters(NULL),
    mReversible(src.mReversible)
{}

CFunction::~CFunction()
{}

bool CFunction::setInfix(const std::string & infix)
{
  if (!CEvaluationTree::setInfix(infix)) return false;
  if (!initVariables()) return false;

  return true;
}

bool CFunction::compile()
{return compileNodes();}

unsigned C_INT32 CFunction::getVariableIndex(const std::string & name) const
  {
    CFunctionParameter::DataType VariableType;
    return mVariables.findParameterByName(name, VariableType);
  }

const C_FLOAT64 & CFunction::getVariableValue(const unsigned C_INT32 & index) const
  {return *(*mpCallParameters)[index].value;}

void CFunction::setReversible(const TriLogic & reversible)
{mReversible = reversible;}

const TriLogic & CFunction::isReversible() const
  {return mReversible;}

CFunctionParameters & CFunction::getVariables()
{return mVariables;}

const CFunctionParameters & CFunction::getVariables() const
  {return mVariables;}

bool CFunction::addVariable(const std::string & name,
                            const std::string & usage,
                            const CFunctionParameter::DataType & type)
{return mVariables.add(name, type, usage);}

CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions()
{return mUsageDescriptions;}

const CCopasiVectorNS < CUsageRange > & CFunction::getUsageDescriptions() const
  {return mUsageDescriptions;}

const C_FLOAT64 & CFunction::calcValue(const CCallParameters<C_FLOAT64> & callParameters)
{
  mpCallParameters = & callParameters;

  try
    {
      return mValue = mpRoot->value();
    }
  catch (...)
    {
      return mValue = std::numeric_limits<C_FLOAT64>::quiet_NaN();
    }
}

bool CFunction::dependsOn(const C_FLOAT64 * parameter,
                          const CCallParameters<C_FLOAT64> & callParameters) const
  {
    CCallParameters<C_FLOAT64>::const_iterator it = callParameters.begin();
    CCallParameters<C_FLOAT64>::const_iterator end = callParameters.end();

    while (it != end && parameter != it->value) it++;

    if (it != end)
      return true;
    else
      return false;
  }

void CFunction::addUsage(const std::string& usage,
                         const unsigned C_INT32 & lowerBound,
                         const unsigned C_INT32 & upperBound)
{
  CUsageRange *u;
  u = new CUsageRange();
  u->setUsage(usage);
  u->setLow(lowerBound);
  u->setHigh(upperBound);
  mUsageDescriptions.add(u);
}

void CFunction::load(CReadConfig & configBuffer,
                     CReadConfig::Mode mode)
{
  //  cleanup();

  if (configBuffer.getVersion() < "4")
    {
      C_INT32 Type;
      CUsageRange UsageDescription;

      mode = CReadConfig::SEARCH;
      configBuffer.getVariable("User-defined", "C_INT32", &Type, mode);

      switch (Type)
        {
        case 1:
          setType(UserDefined);
          break;

        default:
          fatalError();
        }

      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);

      configBuffer.getVariable("Substrates", "C_INT32", &Type);
      UsageDescription.setUsage("SUBSTRATE");
      if (Type == 0)
        UsageDescription.setRange(Type, CRange::Infinity);
      else
        UsageDescription.setRange(Type);

      if (!mUsageDescriptions.add(UsageDescription) &&
          CCopasiMessage::peekLastMessage().getNumber() == MCCopasiVector + 2)
        CCopasiMessage::getLastMessage();

      configBuffer.getVariable("Products", "C_INT32", &Type);
      UsageDescription.setUsage("PRODUCT");
      if (Type == 0)
        UsageDescription.setRange(Type, CRange::Infinity);
      else
        UsageDescription.setRange(Type);

      if (!mUsageDescriptions.add(UsageDescription) &&
          CCopasiMessage::peekLastMessage().getNumber() == MCCopasiVector + 2)
        CCopasiMessage::getLastMessage();

      mode = CReadConfig::SEARCH;
    }
  else
    fatalError();

  std::string tmp;
  configBuffer.getVariable("FunctionName", "string", &tmp, mode);
  setObjectName(tmp);

  configBuffer.getVariable("Description", "string", &tmp);
  setInfix(tmp);

  if (configBuffer.getVersion() >= "4")
    {
      unsigned C_INT32 Size;
      configBuffer.getVariable("Reversible", "C_INT32", &mReversible);
      configBuffer.getVariable("UsageDescriptionSize", "C_INT32", &Size);
      mUsageDescriptions.load(configBuffer, Size);
      mVariables.load(configBuffer);
    }

  // For older file version the parameters have to be build from information
  // dependend on the function type. Luckilly, only user defined functions are
  // the only ones occuring in those files.

  guessModifierUsageRange();
}

bool CFunction::initVariables()
{
  if (mpNodeList == NULL) return false;

  std::vector< CEvaluationNode * >::iterator it
  = mpNodeList->begin();
  std::vector< CEvaluationNode * >::iterator end
  = mpNodeList->end();

  CFunctionParameters NewVariables;

  for (; it != end; ++it)
    if (CEvaluationNode::type((*it)->getType()) == CEvaluationNode::VARIABLE)
      {
        mVariables.add((*it)->getData(), CFunctionParameter::FLOAT64, "VARIABLE");
        NewVariables.add((*it)->getData(), CFunctionParameter::FLOAT64, "VARIABLE");
      }

  CFunctionParameter::DataType Type;
  unsigned C_INT32 i;
  for (i = mVariables.size() - 1; i < C_INVALID_INDEX; i--)
    if (NewVariables.findParameterByName(mVariables[i]->getObjectName(), Type) == C_INVALID_INDEX)
      mVariables.remove(mVariables[i]->getObjectName());

  return true;
}

bool CFunction::guessModifierUsageRange()
{
  unsigned C_INT32 imax = mVariables.getNumberOfParametersByUsage("MODIFIER");

  if (imax != 0)
    {
      unsigned C_INT32 pos = 0;

      if (mVariables.getParameterByUsage("MODIFIER", pos).getType() == CFunctionParameter::VFLOAT64)
        addUsage("MODIFIER", 0, CRange::Infinity);
      else
        addUsage("MODIFIER", imax, CRange::NoRange);
    }

  return true;
}
<|endoftext|>


<commit_before>#include "NJU9101.h"

NJU9101Class NJU9101;

NJU9101Class::NJU9101Class(uint8_t slvAddrBase) {
  this->slaveAddress = slvAddrBase;
}

NJU9101Class::~NJU9101Class() {
}

void NJU9101Class::begin(uint8_t slvAddr) {
  this->slaveAddress |= (slvAddr & 0x07);
  Wire.begin();
}

void NJU9101Class::end() {
}

void NJU9101Class::read(Address address, uint8_t data[], size_t length) {
  Wire.beginTransmission(this->slaveAddress);
  Wire.write((uint8_t)address);
  Wire.endTransmission(false);
  Wire.requestFrom(this->slaveAddress, (uint8_t)length, (uint8_t)false);
  for (int i = 0; i < length; i++) {
    data[i] = Wire.read();
  }
  Wire.endTransmission(true);
}

void NJU9101Class::write(Address address, uint8_t data[], size_t length) {
  Wire.beginTransmission(this->slaveAddress);
  Wire.write((uint8_t)address);
  for (int i = 0; i < length; i++) {
    Wire.write(data[i]);
  }
  Wire.endTransmission(true);
}

bool NJU9101Class::reset() {
  uint8_t wd = CTRL_RST;
  uint8_t rd = 0;
  NJU9101Class::write(NJU9101_ADDRESS_CTRL, &wd, 1);
  // wait for boot
  do {
    NJU9101Class::read(NJU9101_ADDRESS_STATUS, &rd, 1);
    if (rd == 0xff) {
      // I2C read will be failed.
      return false;
    }
  } while (rd & STATUS_BOOT);
  return true;
}

bool NJU9101Class::awake_osc() {
  uint8_t wd = BLKCTRL_OSC_POWER_DOWN_NEVER;
  uint8_t rd = 0;
  NJU9101Class::write(NJU9101_ADDRESS_BLKCTRL, &wd, 1);
  // wait for wake up
  do {
    NJU9101Class::read(NJU9101_ADDRESS_STATUS, &rd, 1);
    if (rd == 0xff) {
      // I2C read will be failed.
      return false;
    }
  } while ((rd & STATUS_CLKRUN) == 0);
  return true;
}

bool NJU9101Class::wait_eoc() {
  uint8_t rd = 0;
  do {
    NJU9101Class::read(NJU9101_ADDRESS_STATUS, &rd, 1);
    if (rd == 0xff) {
      // I2C read will be failed.
      return false;
    }
  } while (rd & STATUS_RDYB);
  return true;
}
<commit_msg>Add explicit this pointer<commit_after>#include "NJU9101.h"

NJU9101Class NJU9101;

NJU9101Class::NJU9101Class(uint8_t slvAddrBase) {
  this->slaveAddress = slvAddrBase;
}

NJU9101Class::~NJU9101Class() {
}

void NJU9101Class::begin(uint8_t slvAddr) {
  this->slaveAddress |= (slvAddr & 0x07);
  Wire.begin();
}

void NJU9101Class::end() {
}

void NJU9101Class::read(Address address, uint8_t data[], size_t length) {
  Wire.beginTransmission(this->slaveAddress);
  Wire.write((uint8_t)address);
  Wire.endTransmission(false);
  Wire.requestFrom(this->slaveAddress, (uint8_t)length, (uint8_t)false);
  for (int i = 0; i < length; i++) {
    data[i] = Wire.read();
  }
  Wire.endTransmission(true);
}

void NJU9101Class::write(Address address, uint8_t data[], size_t length) {
  Wire.beginTransmission(this->slaveAddress);
  Wire.write((uint8_t)address);
  for (int i = 0; i < length; i++) {
    Wire.write(data[i]);
  }
  Wire.endTransmission(true);
}

bool NJU9101Class::reset() {
  uint8_t wd = CTRL_RST;
  uint8_t rd = 0;
  this->write(NJU9101_ADDRESS_CTRL, &wd, 1);
  // wait for boot
  do {
    this->read(NJU9101_ADDRESS_STATUS, &rd, 1);
    if (rd == 0xff) {
      // I2C read will be failed.
      return false;
    }
  } while (rd & STATUS_BOOT);
  return true;
}

bool NJU9101Class::awake_osc() {
  uint8_t wd = BLKCTRL_OSC_POWER_DOWN_NEVER;
  uint8_t rd = 0;
  this->write(NJU9101_ADDRESS_BLKCTRL, &wd, 1);
  // wait for wake up
  do {
    this->read(NJU9101_ADDRESS_STATUS, &rd, 1);
    if (rd == 0xff) {
      // I2C read will be failed.
      return false;
    }
  } while ((rd & STATUS_CLKRUN) == 0);
  return true;
}

bool NJU9101Class::wait_eoc() {
  uint8_t rd = 0;
  do {
    this->read(NJU9101_ADDRESS_STATUS, &rd, 1);
    if (rd == 0xff) {
      // I2C read will be failed.
      return false;
    }
  } while (rd & STATUS_RDYB);
  return true;
}
<|endoftext|>