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

#include <algorithm>
#include <string>

#include "base/command_line.h"
#include "base/file_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/configuration_policy_pref_store.h"
#include "chrome/browser/policy/cloud_policy_subsystem.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/user_policy_cache.h"
#include "chrome/browser/policy/user_policy_identity_strategy.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "net/url_request/url_request_context_getter.h"

namespace {

const FilePath::CharType kPolicyDir[] = FILE_PATH_LITERAL("Device Management");
const FilePath::CharType kTokenCacheFile[] = FILE_PATH_LITERAL("Token");
const FilePath::CharType kPolicyCacheFile[] = FILE_PATH_LITERAL("Policy");

}  // namespace

namespace policy {

ProfilePolicyConnector::ProfilePolicyConnector(Profile* profile)
    : profile_(profile) {
  // TODO(mnissler): We access the file system here. The cloud policy context
  // below needs to do so anyway, since it needs to read the policy cache from
  // disk. If this proves to be a problem, we need to do this initialization
  // asynchronously on the file thread and put in synchronization that allows us
  // to wait for the cache to be read during the browser startup code paths.
  // Another option would be to provide a generic IO-safe initializer called
  // from the PrefService that we could hook up with through the policy
  // provider.
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDeviceManagementUrl)) {
    FilePath policy_cache_dir(profile_->GetPath());
    policy_cache_dir = policy_cache_dir.Append(kPolicyDir);
    if (!file_util::CreateDirectory(policy_cache_dir)) {
      LOG(WARNING) << "Failed to create policy state dir "
                   << policy_cache_dir.value()
                   << ", skipping cloud policy initialization.";
      return;
    }

    identity_strategy_.reset(new UserPolicyIdentityStrategy(
        profile_,
        policy_cache_dir.Append(kTokenCacheFile)));
    cloud_policy_subsystem_.reset(new CloudPolicySubsystem(
        identity_strategy_.get(),
        new UserPolicyCache(policy_cache_dir.Append(kPolicyCacheFile))));

    BrowserPolicyConnector* browser_connector =
        g_browser_process->browser_policy_connector();

    managed_cloud_provider_.reset(new MergingPolicyProvider(
        browser_connector->GetManagedCloudProvider(),
        cloud_policy_subsystem_->GetManagedPolicyProvider()));
    recommended_cloud_provider_.reset(new MergingPolicyProvider(
        browser_connector->GetRecommendedCloudProvider(),
        cloud_policy_subsystem_->GetRecommendedPolicyProvider()));
  }
}

ProfilePolicyConnector::~ProfilePolicyConnector() {
  managed_cloud_provider_.reset();
  recommended_cloud_provider_.reset();
  cloud_policy_subsystem_.reset();
  identity_strategy_.reset();
}

void ProfilePolicyConnector::Initialize() {
  // TODO(jkummerow, mnissler): Move this out of the browser startup path.
  if (cloud_policy_subsystem_.get()) {
    cloud_policy_subsystem_->Initialize(profile_->GetPrefs(),
                                        profile_->GetRequestContext());
  }
}

void ProfilePolicyConnector::Shutdown() {
  if (cloud_policy_subsystem_.get())
    cloud_policy_subsystem_->Shutdown();
}

ConfigurationPolicyProvider*
    ProfilePolicyConnector::GetManagedCloudProvider() {
  return managed_cloud_provider_.get();
}

ConfigurationPolicyProvider*
    ProfilePolicyConnector::GetRecommendedCloudProvider() {
  return recommended_cloud_provider_.get();
}

MergingPolicyProvider::MergingPolicyProvider(
    ConfigurationPolicyProvider* browser_policy_provider,
    ConfigurationPolicyProvider* profile_policy_provider)
    : ConfigurationPolicyProvider(
          ConfigurationPolicyPrefStore::GetChromePolicyDefinitionList()),
      browser_policy_provider_(browser_policy_provider),
      profile_policy_provider_(profile_policy_provider),
      browser_registrar_(new ConfigurationPolicyObserverRegistrar()),
      profile_registrar_(new ConfigurationPolicyObserverRegistrar()) {
  browser_registrar_->Init(browser_policy_provider_, this);
  profile_registrar_->Init(profile_policy_provider_, this);
}

MergingPolicyProvider::~MergingPolicyProvider() {
  if (browser_policy_provider_ && profile_policy_provider_) {
    FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
                      observer_list_, OnProviderGoingAway());
  }
}

bool MergingPolicyProvider::Provide(ConfigurationPolicyStoreInterface* store) {
  // First, apply the profile policies and observe if interesting policies
  // have been applied.
  ObservingPolicyStoreInterface observe(store);
  bool rv = profile_policy_provider_->Provide(&observe);

  // Now apply policies from the browser provider, if they were not applied
  // by the profile provider.
  // Currently, these include only the proxy settings.
  FilteringPolicyStoreInterface filter(store, !observe.IsProxyPolicyApplied());
  rv = rv && browser_policy_provider_->Provide(&filter);

  return rv;
}

void MergingPolicyProvider::AddObserver(
    ConfigurationPolicyProvider::Observer* observer) {
  observer_list_.AddObserver(observer);
}

void MergingPolicyProvider::RemoveObserver(
    ConfigurationPolicyProvider::Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

void MergingPolicyProvider::OnUpdatePolicy() {
  FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
                    observer_list_, OnUpdatePolicy());
}

void MergingPolicyProvider::OnProviderGoingAway() {
  if (browser_policy_provider_ && profile_policy_provider_) {
    FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
                      observer_list_, OnProviderGoingAway());
    browser_registrar_.reset();
    profile_registrar_.reset();
    browser_policy_provider_ = NULL;
    profile_policy_provider_ = NULL;
  }
}

}  // namespace policy
<commit_msg>Fix null pointer bug in MergingPolicyProvider.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <algorithm>
#include <string>

#include "base/command_line.h"
#include "base/file_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/configuration_policy_pref_store.h"
#include "chrome/browser/policy/cloud_policy_subsystem.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/user_policy_cache.h"
#include "chrome/browser/policy/user_policy_identity_strategy.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "net/url_request/url_request_context_getter.h"

namespace {

const FilePath::CharType kPolicyDir[] = FILE_PATH_LITERAL("Device Management");
const FilePath::CharType kTokenCacheFile[] = FILE_PATH_LITERAL("Token");
const FilePath::CharType kPolicyCacheFile[] = FILE_PATH_LITERAL("Policy");

}  // namespace

namespace policy {

ProfilePolicyConnector::ProfilePolicyConnector(Profile* profile)
    : profile_(profile) {
  // TODO(mnissler): We access the file system here. The cloud policy context
  // below needs to do so anyway, since it needs to read the policy cache from
  // disk. If this proves to be a problem, we need to do this initialization
  // asynchronously on the file thread and put in synchronization that allows us
  // to wait for the cache to be read during the browser startup code paths.
  // Another option would be to provide a generic IO-safe initializer called
  // from the PrefService that we could hook up with through the policy
  // provider.
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDeviceManagementUrl)) {
    FilePath policy_cache_dir(profile_->GetPath());
    policy_cache_dir = policy_cache_dir.Append(kPolicyDir);
    if (!file_util::CreateDirectory(policy_cache_dir)) {
      LOG(WARNING) << "Failed to create policy state dir "
                   << policy_cache_dir.value()
                   << ", skipping cloud policy initialization.";
      return;
    }

    identity_strategy_.reset(new UserPolicyIdentityStrategy(
        profile_,
        policy_cache_dir.Append(kTokenCacheFile)));
    cloud_policy_subsystem_.reset(new CloudPolicySubsystem(
        identity_strategy_.get(),
        new UserPolicyCache(policy_cache_dir.Append(kPolicyCacheFile))));

    BrowserPolicyConnector* browser_connector =
        g_browser_process->browser_policy_connector();

    managed_cloud_provider_.reset(new MergingPolicyProvider(
        browser_connector->GetManagedCloudProvider(),
        cloud_policy_subsystem_->GetManagedPolicyProvider()));
    recommended_cloud_provider_.reset(new MergingPolicyProvider(
        browser_connector->GetRecommendedCloudProvider(),
        cloud_policy_subsystem_->GetRecommendedPolicyProvider()));
  }
}

ProfilePolicyConnector::~ProfilePolicyConnector() {
  managed_cloud_provider_.reset();
  recommended_cloud_provider_.reset();
  cloud_policy_subsystem_.reset();
  identity_strategy_.reset();
}

void ProfilePolicyConnector::Initialize() {
  // TODO(jkummerow, mnissler): Move this out of the browser startup path.
  if (cloud_policy_subsystem_.get()) {
    cloud_policy_subsystem_->Initialize(profile_->GetPrefs(),
                                        profile_->GetRequestContext());
  }
}

void ProfilePolicyConnector::Shutdown() {
  if (cloud_policy_subsystem_.get())
    cloud_policy_subsystem_->Shutdown();
}

ConfigurationPolicyProvider*
    ProfilePolicyConnector::GetManagedCloudProvider() {
  return managed_cloud_provider_.get();
}

ConfigurationPolicyProvider*
    ProfilePolicyConnector::GetRecommendedCloudProvider() {
  return recommended_cloud_provider_.get();
}

MergingPolicyProvider::MergingPolicyProvider(
    ConfigurationPolicyProvider* browser_policy_provider,
    ConfigurationPolicyProvider* profile_policy_provider)
    : ConfigurationPolicyProvider(
          ConfigurationPolicyPrefStore::GetChromePolicyDefinitionList()),
      browser_policy_provider_(browser_policy_provider),
      profile_policy_provider_(profile_policy_provider),
      browser_registrar_(new ConfigurationPolicyObserverRegistrar()),
      profile_registrar_(new ConfigurationPolicyObserverRegistrar()) {
  if (browser_policy_provider_)
    browser_registrar_->Init(browser_policy_provider_, this);
  if (profile_policy_provider_)
    profile_registrar_->Init(profile_policy_provider_, this);
}

MergingPolicyProvider::~MergingPolicyProvider() {
  if (browser_policy_provider_ || profile_policy_provider_) {
    FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
                      observer_list_, OnProviderGoingAway());
  }
}

bool MergingPolicyProvider::Provide(ConfigurationPolicyStoreInterface* store) {
  // First, apply the profile policies and observe if interesting policies
  // have been applied.
  ObservingPolicyStoreInterface observe(store);
  bool rv = true;
  if (profile_policy_provider_)
    rv = profile_policy_provider_->Provide(&observe);

  // Now apply policies from the browser provider, if they were not applied
  // by the profile provider.
  // Currently, these include only the proxy settings.
  if (browser_policy_provider_) {
    FilteringPolicyStoreInterface filter(store,
                                         !observe.IsProxyPolicyApplied());
    rv = rv && browser_policy_provider_->Provide(&filter);
  }

  return rv;
}

void MergingPolicyProvider::AddObserver(
    ConfigurationPolicyProvider::Observer* observer) {
  observer_list_.AddObserver(observer);
}

void MergingPolicyProvider::RemoveObserver(
    ConfigurationPolicyProvider::Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

void MergingPolicyProvider::OnUpdatePolicy() {
  FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
                    observer_list_, OnUpdatePolicy());
}

void MergingPolicyProvider::OnProviderGoingAway() {
  if (browser_policy_provider_ || profile_policy_provider_) {
    FOR_EACH_OBSERVER(ConfigurationPolicyProvider::Observer,
                      observer_list_, OnProviderGoingAway());
    browser_registrar_.reset();
    profile_registrar_.reset();
    browser_policy_provider_ = NULL;
    profile_policy_provider_ = NULL;
  }
}

}  // namespace policy
<|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 "chrome/browser/ui/views/aura/caps_lock_handler.h"

#include "content/public/browser/browser_thread.h"

// TODO(yusukes): Support Ash on Windows.
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#endif

#if defined(OS_CHROMEOS)
CapsLockHandler::CapsLockHandler(chromeos::input_method::XKeyboard* xkeyboard)
    : xkeyboard_(xkeyboard),
      is_running_on_chromeos_(
          chromeos::system::runtime_environment::IsRunningOnChromeOS()),
      caps_lock_is_on_(xkeyboard_->CapsLockIsEnabled()) {
  chromeos::SystemKeyEventListener* system_event_listener =
      chromeos::SystemKeyEventListener::GetInstance();
  // SystemKeyEventListener should be instantiated when we're running on Chrome
  // OS.
  DCHECK(!is_running_on_chromeos_ || system_event_listener);
  if (system_event_listener)
    system_event_listener->AddCapsLockObserver(this);
}
#endif

CapsLockHandler::~CapsLockHandler() {
#if defined(OS_CHROMEOS)
  chromeos::SystemKeyEventListener* system_event_listener =
      chromeos::SystemKeyEventListener::GetInstance();
  if (system_event_listener)
    system_event_listener->RemoveCapsLockObserver(this);
#endif
}

bool CapsLockHandler::HandleToggleCapsLock() {
#if defined(OS_CHROMEOS)
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (is_running_on_chromeos_) {
    // TODO(yusukes): Do not change Caps Lock status and just return false if
    // spoken feedback is enabled (crosbug.com/110127).
    xkeyboard_->SetCapsLockEnabled(!caps_lock_is_on_);
    return true;  // consume the shortcut key.
  }
#else
  NOTIMPLEMENTED();
#endif
  return false;
}

#if defined(OS_CHROMEOS)
void CapsLockHandler::OnCapsLockChange(bool enabled) {
  caps_lock_is_on_ = enabled;
}
#endif
<commit_msg>Ignore Shift+Search when spoken feedback is enabled.<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 "chrome/browser/ui/views/aura/caps_lock_handler.h"

#include "content/public/browser/browser_thread.h"

// TODO(yusukes): Support Ash on Windows.
#if defined(OS_CHROMEOS)
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
#endif

#if defined(OS_CHROMEOS)
CapsLockHandler::CapsLockHandler(chromeos::input_method::XKeyboard* xkeyboard)
    : xkeyboard_(xkeyboard),
      is_running_on_chromeos_(
          chromeos::system::runtime_environment::IsRunningOnChromeOS()),
      caps_lock_is_on_(xkeyboard_->CapsLockIsEnabled()) {
  chromeos::SystemKeyEventListener* system_event_listener =
      chromeos::SystemKeyEventListener::GetInstance();
  // SystemKeyEventListener should be instantiated when we're running on Chrome
  // OS.
  DCHECK(!is_running_on_chromeos_ || system_event_listener);
  if (system_event_listener)
    system_event_listener->AddCapsLockObserver(this);
}
#endif

CapsLockHandler::~CapsLockHandler() {
#if defined(OS_CHROMEOS)
  chromeos::SystemKeyEventListener* system_event_listener =
      chromeos::SystemKeyEventListener::GetInstance();
  if (system_event_listener)
    system_event_listener->RemoveCapsLockObserver(this);
#endif
}

bool CapsLockHandler::HandleToggleCapsLock() {
#if defined(OS_CHROMEOS)
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (is_running_on_chromeos_ &&
      // When spoken feedback is enabled, the Search key is used as an
      // accessibility modifier key.
      !g_browser_process->local_state()->GetBoolean(
          prefs::kSpokenFeedbackEnabled)) {
    xkeyboard_->SetCapsLockEnabled(!caps_lock_is_on_);
    return true;  // consume the shortcut key.
  }
#else
  NOTIMPLEMENTED();
#endif
  return false;
}

#if defined(OS_CHROMEOS)
void CapsLockHandler::OnCapsLockChange(bool enabled) {
  caps_lock_is_on_ = enabled;
}
#endif
<|endoftext|>


<commit_before>/*********************************************************************
 *
 * Condor ClassAd library
 * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI, and Rajesh Raman.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General
 * Public License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 *********************************************************************/

#include "common.h"
#include "operators.h"
#include "value.h"

BEGIN_NAMESPACE( classad )

const double Value::ScaleFactor[] = {
	1.0, 						// none
	1.0, 						// B
	1024.0,						// Kilo
	1024.0*1024.0, 				// Mega
	1024.0*1024.0*1024.0, 		// Giga
	1024.0*1024.0*1024.0*1024.0	// Terra
};

Value::
Value( )
{
	valueType = UNDEFINED_VALUE;
	booleanValue = false;
	integerValue = 0;
	realValue = 0.0;
	listValue = NULL;
	classadValue = NULL;
	timeValueSecs = 0;
}

Value::
~Value()
{
}

void Value::
Clear()
{
	switch( valueType ) {
		case LIST_VALUE:
			// list values live in the evaluation environment, so they must
			// never be explicitly destroyed
			listValue = NULL;
			break;

		case CLASSAD_VALUE:
			// classad values live in the evaluation environment, so they must
			// never be explicitly destroyed
			classadValue = NULL;
			break;

		case STRING_VALUE:
			strValue = "";
			break;

		default:
			valueType = UNDEFINED_VALUE;
	}
	valueType 	= UNDEFINED_VALUE;
}

bool Value::
IsNumber (int &i) const
{
	switch (valueType) {
		case INTEGER_VALUE:
			i = integerValue;
			return true;

		case REAL_VALUE:
			i = (int) realValue;	// truncation
			return true;

		default:
			return false;
	}
}

bool Value::
IsNumber (double &r) const
{
	switch (valueType) {
		case INTEGER_VALUE:
			r = (double) integerValue;
			return true;

		case REAL_VALUE:
			r = realValue;
			return true;

		default:
			return false;
	}
}

void Value::
CopyFrom( const Value &val )
{
	valueType = val.valueType;
	switch (val.valueType) {
		case STRING_VALUE:
			strValue = val.strValue;
			return;

		case BOOLEAN_VALUE:
			booleanValue = val.booleanValue;
			return;

		case INTEGER_VALUE:
			integerValue = val.integerValue;
			return;

		case REAL_VALUE:
			realValue = val.realValue;
			return;

		case UNDEFINED_VALUE:
		case ERROR_VALUE:
			return;

		case LIST_VALUE:
			listValue = val.listValue;
			return;

		case CLASSAD_VALUE:
			classadValue = val.classadValue;
			return;

		case ABSOLUTE_TIME_VALUE:
		case RELATIVE_TIME_VALUE:
			timeValueSecs = val.timeValueSecs;
			return;

		default:
			SetUndefinedValue ();
	}
}

void Value::
SetRealValue (double r)
{
    valueType=REAL_VALUE;
    realValue = r;
}

void Value::
SetBooleanValue( bool b )
{
	valueType = BOOLEAN_VALUE;
	booleanValue = b;
}

void Value::
SetIntegerValue (int i)
{
    valueType=INTEGER_VALUE;
    integerValue = i;
}

void Value::
SetUndefinedValue (void)
{
    valueType=UNDEFINED_VALUE;
}

void Value::
SetErrorValue (void)
{
    valueType=ERROR_VALUE;
}

void Value::
SetStringValue( const string &s )
{
	valueType = STRING_VALUE;
	strValue = s;
}

void Value::
SetStringValue( const char *s )
{
	valueType = STRING_VALUE;
	strValue = s;
}

void Value::
SetListValue( const ExprList *l)
{
    valueType = LIST_VALUE;
    listValue = l;
}

void Value::
SetClassAdValue( ClassAd *ad )
{
	valueType = CLASSAD_VALUE;
	classadValue = ad;
}

void Value::
SetRelativeTimeValue( time_t rsecs )
{
	valueType = RELATIVE_TIME_VALUE;
	timeValueSecs = rsecs;
}

void Value::
SetAbsoluteTimeValue( time_t asecs )
{
	valueType = ABSOLUTE_TIME_VALUE;
	timeValueSecs = asecs;
}

ostream& operator<<(ostream &stream, Value &value)
{
	switch (value.valueType) {
	case Value::NULL_VALUE:
		stream << "(null)";
		break;
	case Value::ERROR_VALUE:
		stream << "error";
		break;
	case Value::UNDEFINED_VALUE:
		stream << "undefined";
		break;
	case Value::BOOLEAN_VALUE:
		if (value.booleanValue) {
			stream << "true";
		} else {
			stream << "false";
		}
		break;
	case Value::INTEGER_VALUE:
		stream << value.integerValue;
		break;
	case Value::REAL_VALUE:
		printf("%18f", value.realValue);
		break;
	case Value::RELATIVE_TIME_VALUE:
		stream << "time value";
		break;
	case Value::ABSOLUTE_TIME_VALUE:
		stream << "time value";
		break;
	case Value::STRING_VALUE:
		stream << value.strValue;
		break;
	case Value::CLASSAD_VALUE:
		stream << "classad value";
		break;
	case Value::LIST_VALUE:
		stream << "list value";
		break;
	}

	return stream;
}

END_NAMESPACE // classad
<commit_msg>Include iostream and added a "using namepsace std;" to make GCC 3.0 happier when compiling the standalone distribution.<commit_after>/*********************************************************************
 *
 * Condor ClassAd library
 * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI, and Rajesh Raman.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General
 * Public License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 *********************************************************************/

#include "common.h"
#include "operators.h"
#include "value.h"
#include <iostream>

using namespace std;

BEGIN_NAMESPACE( classad )

const double Value::ScaleFactor[] = {
	1.0, 						// none
	1.0, 						// B
	1024.0,						// Kilo
	1024.0*1024.0, 				// Mega
	1024.0*1024.0*1024.0, 		// Giga
	1024.0*1024.0*1024.0*1024.0	// Terra
};

Value::
Value( )
{
	valueType = UNDEFINED_VALUE;
	booleanValue = false;
	integerValue = 0;
	realValue = 0.0;
	listValue = NULL;
	classadValue = NULL;
	timeValueSecs = 0;
}

Value::
~Value()
{
}

void Value::
Clear()
{
	switch( valueType ) {
		case LIST_VALUE:
			// list values live in the evaluation environment, so they must
			// never be explicitly destroyed
			listValue = NULL;
			break;

		case CLASSAD_VALUE:
			// classad values live in the evaluation environment, so they must
			// never be explicitly destroyed
			classadValue = NULL;
			break;

		case STRING_VALUE:
			strValue = "";
			break;

		default:
			valueType = UNDEFINED_VALUE;
	}
	valueType 	= UNDEFINED_VALUE;
}

bool Value::
IsNumber (int &i) const
{
	switch (valueType) {
		case INTEGER_VALUE:
			i = integerValue;
			return true;

		case REAL_VALUE:
			i = (int) realValue;	// truncation
			return true;

		default:
			return false;
	}
}

bool Value::
IsNumber (double &r) const
{
	switch (valueType) {
		case INTEGER_VALUE:
			r = (double) integerValue;
			return true;

		case REAL_VALUE:
			r = realValue;
			return true;

		default:
			return false;
	}
}

void Value::
CopyFrom( const Value &val )
{
	valueType = val.valueType;
	switch (val.valueType) {
		case STRING_VALUE:
			strValue = val.strValue;
			return;

		case BOOLEAN_VALUE:
			booleanValue = val.booleanValue;
			return;

		case INTEGER_VALUE:
			integerValue = val.integerValue;
			return;

		case REAL_VALUE:
			realValue = val.realValue;
			return;

		case UNDEFINED_VALUE:
		case ERROR_VALUE:
			return;

		case LIST_VALUE:
			listValue = val.listValue;
			return;

		case CLASSAD_VALUE:
			classadValue = val.classadValue;
			return;

		case ABSOLUTE_TIME_VALUE:
		case RELATIVE_TIME_VALUE:
			timeValueSecs = val.timeValueSecs;
			return;

		default:
			SetUndefinedValue ();
	}
}

void Value::
SetRealValue (double r)
{
    valueType=REAL_VALUE;
    realValue = r;
}

void Value::
SetBooleanValue( bool b )
{
	valueType = BOOLEAN_VALUE;
	booleanValue = b;
}

void Value::
SetIntegerValue (int i)
{
    valueType=INTEGER_VALUE;
    integerValue = i;
}

void Value::
SetUndefinedValue (void)
{
    valueType=UNDEFINED_VALUE;
}

void Value::
SetErrorValue (void)
{
    valueType=ERROR_VALUE;
}

void Value::
SetStringValue( const string &s )
{
	valueType = STRING_VALUE;
	strValue = s;
}

void Value::
SetStringValue( const char *s )
{
	valueType = STRING_VALUE;
	strValue = s;
}

void Value::
SetListValue( const ExprList *l)
{
    valueType = LIST_VALUE;
    listValue = l;
}

void Value::
SetClassAdValue( ClassAd *ad )
{
	valueType = CLASSAD_VALUE;
	classadValue = ad;
}

void Value::
SetRelativeTimeValue( time_t rsecs )
{
	valueType = RELATIVE_TIME_VALUE;
	timeValueSecs = rsecs;
}

void Value::
SetAbsoluteTimeValue( time_t asecs )
{
	valueType = ABSOLUTE_TIME_VALUE;
	timeValueSecs = asecs;
}

ostream& operator<<(ostream &stream, Value &value)
{
	switch (value.valueType) {
	case Value::NULL_VALUE:
		stream << "(null)";
		break;
	case Value::ERROR_VALUE:
		stream << "error";
		break;
	case Value::UNDEFINED_VALUE:
		stream << "undefined";
		break;
	case Value::BOOLEAN_VALUE:
		if (value.booleanValue) {
			stream << "true";
		} else {
			stream << "false";
		}
		break;
	case Value::INTEGER_VALUE:
		stream << value.integerValue;
		break;
	case Value::REAL_VALUE:
		printf("%18f", value.realValue);
		break;
	case Value::RELATIVE_TIME_VALUE:
		stream << "time value";
		break;
	case Value::ABSOLUTE_TIME_VALUE:
		stream << "time value";
		break;
	case Value::STRING_VALUE:
		stream << value.strValue;
		break;
	case Value::CLASSAD_VALUE:
		stream << "classad value";
		break;
	case Value::LIST_VALUE:
		stream << "list value";
		break;
	}

	return stream;
}

END_NAMESPACE // classad
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: formattedcontrol.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-27 17:02:53 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef TOOLKIT_FORMATTED_CONTROL_HXX
#define TOOLKIT_FORMATTED_CONTROL_HXX

#ifndef _TOOLKIT_HELPER_UNOCONTROLS_HXX_
#include <toolkit/controls/unocontrols.hxx>
#endif
#ifndef _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_
#include <toolkit/controls/unocontrolmodel.hxx>
#endif
#ifndef _TOOLKIT_HELPER_SERVICENAMES_HXX_
#include <toolkit/helper/servicenames.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_XSPINFIELD_HPP_
#include <com/sun/star/awt/XSpinField.hpp>
#endif

//........................................................................
namespace toolkit
{
//........................................................................

    // ===================================================================
    // = UnoControlFormattedFieldModel
    // ===================================================================
    class UnoControlFormattedFieldModel : public UnoControlModel
    {
    protected:
        ::com::sun::star::uno::Any      ImplGetDefaultValue( sal_uInt16 nPropId ) const;
        ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    protected:
        sal_Bool SAL_CALL convertFastPropertyValue(
                    ::com::sun::star::uno::Any& rConvertedValue,
                    ::com::sun::star::uno::Any& rOldValue,
                    sal_Int32 nPropId,
                    const ::com::sun::star::uno::Any& rValue
                ) throw (::com::sun::star::lang::IllegalArgumentException);

    public:
                            UnoControlFormattedFieldModel();
                            UnoControlFormattedFieldModel( const UnoControlFormattedFieldModel& rModel ) : UnoControlModel( rModel ) {;}

        UnoControlModel*    Clone() const { return new UnoControlFormattedFieldModel( *this ); }

        // ::com::sun::star::io::XPersistObject
        ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::beans::XMultiPropertySet
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::lang::XServiceInfo
        DECLIMPL_SERVICEINFO_DERIVED( UnoControlFormattedFieldModel, UnoControlModel, szServiceName2_UnoControlFormattedFieldModel )
    };

    // ===================================================================
    // = UnoFormattedFieldControl
    // ===================================================================
    class UnoFormattedFieldControl : public UnoSpinFieldControl
    {
    public:
                            UnoFormattedFieldControl();
        ::rtl::OUString     GetComponentServiceName();

        // ::com::sun::star::awt::XTextListener
        void SAL_CALL textChanged( const ::com::sun::star::awt::TextEvent& rEvent ) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::lang::XServiceInfo
        DECLIMPL_SERVICEINFO_DERIVED( UnoFormattedFieldControl, UnoEditControl, szServiceName2_UnoControlFormattedField )
    };

//........................................................................
}   // namespace toolkit
//........................................................................

#endif // TOOLKIT_FORMATTED_CONTROL_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.336); FILE MERGED 2005/09/05 16:57:38 rt 1.2.336.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formattedcontrol.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:48:35 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef TOOLKIT_FORMATTED_CONTROL_HXX
#define TOOLKIT_FORMATTED_CONTROL_HXX

#ifndef _TOOLKIT_HELPER_UNOCONTROLS_HXX_
#include <toolkit/controls/unocontrols.hxx>
#endif
#ifndef _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_
#include <toolkit/controls/unocontrolmodel.hxx>
#endif
#ifndef _TOOLKIT_HELPER_SERVICENAMES_HXX_
#include <toolkit/helper/servicenames.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_XSPINFIELD_HPP_
#include <com/sun/star/awt/XSpinField.hpp>
#endif

//........................................................................
namespace toolkit
{
//........................................................................

    // ===================================================================
    // = UnoControlFormattedFieldModel
    // ===================================================================
    class UnoControlFormattedFieldModel : public UnoControlModel
    {
    protected:
        ::com::sun::star::uno::Any      ImplGetDefaultValue( sal_uInt16 nPropId ) const;
        ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    protected:
        sal_Bool SAL_CALL convertFastPropertyValue(
                    ::com::sun::star::uno::Any& rConvertedValue,
                    ::com::sun::star::uno::Any& rOldValue,
                    sal_Int32 nPropId,
                    const ::com::sun::star::uno::Any& rValue
                ) throw (::com::sun::star::lang::IllegalArgumentException);

    public:
                            UnoControlFormattedFieldModel();
                            UnoControlFormattedFieldModel( const UnoControlFormattedFieldModel& rModel ) : UnoControlModel( rModel ) {;}

        UnoControlModel*    Clone() const { return new UnoControlFormattedFieldModel( *this ); }

        // ::com::sun::star::io::XPersistObject
        ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::beans::XMultiPropertySet
        ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::lang::XServiceInfo
        DECLIMPL_SERVICEINFO_DERIVED( UnoControlFormattedFieldModel, UnoControlModel, szServiceName2_UnoControlFormattedFieldModel )
    };

    // ===================================================================
    // = UnoFormattedFieldControl
    // ===================================================================
    class UnoFormattedFieldControl : public UnoSpinFieldControl
    {
    public:
                            UnoFormattedFieldControl();
        ::rtl::OUString     GetComponentServiceName();

        // ::com::sun::star::awt::XTextListener
        void SAL_CALL textChanged( const ::com::sun::star::awt::TextEvent& rEvent ) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::lang::XServiceInfo
        DECLIMPL_SERVICEINFO_DERIVED( UnoFormattedFieldControl, UnoEditControl, szServiceName2_UnoControlFormattedField )
    };

//........................................................................
}   // namespace toolkit
//........................................................................

#endif // TOOLKIT_FORMATTED_CONTROL_HXX
<|endoftext|>


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

#include "RequestManager.h"
#include "NebulaLog.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RequestManager::ImagePoolInfo::execute(
    xmlrpc_c::paramList const& paramList,
    xmlrpc_c::value *   const  retval)
{
    string        session;

    ostringstream oss;
    ostringstream where_string;

    int           rc;
    int           uid;
    int           filter_flag;

    /*   -- RPC specific vars --  */
    vector<xmlrpc_c::value> arrayData;
    xmlrpc_c::value_array * arrayresult;

    NebulaLog::log("ReM",Log::DEBUG,"ImagePoolInfo method invoked");

    // Get the parameters
    session     = xmlrpc_c::value_string(paramList.getString(0));
    filter_flag = xmlrpc_c::value_int(paramList.getInt(1));

    // Check if it is a valid user
    rc = ImagePoolInfo::upool->authenticate(session);

    if ( rc == -1 )
    {
        goto error_authenticate;
    }

    uid = rc;

    where_string.str("");

    /** Filter flag meaning table
     *     -3 :: All Images (just for oneadmin)
     *     -2  :: User's Images AND public images
     *     -1  :: User's Images exclusively
     *    >=0  :: UID User's Images (just for oneadmin)
     **/
    if ( filter_flag < -3 )
    {
        goto error_filter_flag;
    }

    switch(filter_flag)
    {
        case -3:
            if ( uid != 0 )
            {
                goto error_authorization;
            }
            break;
        case -2:
            where_string << "UID=" << uid << " OR oid IN ( SELECT oid " <<
                            "FROM " <<
                            ImagePoolInfo::ipool->get_template_table_name()  <<
                            " WHERE name = 'PUBLIC' AND value = 'Yes')";
            break;
        case -1:
            where_string << "UID=" << uid;
            break;
        default:
            where_string << "UID=" << filter_flag;
    }

    // Perform the allocation in the vmpool
    rc = ImagePoolInfo::ipool->dump(oss,where_string.str());

    if ( rc != 0 )
    {
        goto error_dump;
    }

    //All nice, return the host info to the client
    arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS
    arrayData.push_back(xmlrpc_c::value_string(oss.str()));

    arrayresult = new xmlrpc_c::value_array(arrayData);

    // Copy arrayresult into retval mem space
    *retval = *arrayresult;

    // and get rid of the original
    delete arrayresult;

    return;

error_authenticate:
    oss << "User not authenticated, ImagePoolInfo call aborted.";
    goto error_common;

error_authorization:
    oss << "User not authorized to perform this operation.";
    goto error_common;

error_filter_flag:
    oss << "Incorrect filter_flag, must be >= 3.";
    goto error_common;

error_dump:
    oss << "Error getting virtual network pool";
    goto error_common;

error_common:

    arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
    arrayData.push_back(xmlrpc_c::value_string(oss.str()));

    NebulaLog::log("ReM",Log::ERROR,oss);

    xmlrpc_c::value_array arrayresult_error(arrayData);

    *retval = arrayresult_error;

    return;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<commit_msg>feature #200: Changed ImagePool Info method to be consistent with other pools.<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "RequestManager.h"
#include "NebulaLog.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RequestManager::ImagePoolInfo::execute(
    xmlrpc_c::paramList const& paramList,
    xmlrpc_c::value *   const  retval)
{
    string        session;

    ostringstream oss;
    ostringstream where_string;

    int           rc;
    int           uid;
    int           filter_flag;

    /*   -- RPC specific vars --  */
    vector<xmlrpc_c::value> arrayData;
    xmlrpc_c::value_array * arrayresult;

    NebulaLog::log("ReM",Log::DEBUG,"ImagePoolInfo method invoked");

    // Get the parameters
    session     = xmlrpc_c::value_string(paramList.getString(0));
    filter_flag = xmlrpc_c::value_int(paramList.getInt(1));

    // Check if it is a valid user
    rc = ImagePoolInfo::upool->authenticate(session);

    if ( rc == -1 )
    {
        goto error_authenticate;
    }

    uid = rc;

    where_string.str("");

    /** Filter flag meaning table
     *      -2 :: All Images (just for oneadmin)
     *      -1 :: User's Images AND public images belonging to any user
     *    >= 0 :: UID User's Images (just for oneadmin)
     **/
    if ( filter_flag < -2 )
    {
        goto error_filter_flag;
    }

    switch(filter_flag)
    {
        case -2:
            if ( uid != 0 )
            {
                goto error_authorization;
            }
            // where remains empty.
            break;
        case -1:
            where_string << "UID=" << uid << " OR public = 'YES'";
            break;
        default:
            // Only oneadmin or the user can list a specific user's images.
            if ( uid != 0 && uid != filter_flag )
            {
                goto error_authorization;
            }
            where_string << "UID=" << filter_flag;
    }

    // Call the image pool dump
    rc = ImagePoolInfo::ipool->dump(oss,where_string.str());

    if ( rc != 0 )
    {
        goto error_dump;
    }

    // All nice, return pool info to the client
    arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS
    arrayData.push_back(xmlrpc_c::value_string(oss.str()));

    arrayresult = new xmlrpc_c::value_array(arrayData);

    // Copy arrayresult into retval mem space
    *retval = *arrayresult;

    // and get rid of the original
    delete arrayresult;

    return;

error_authenticate:
    oss << "User not authenticated, ImagePoolInfo call aborted.";
    goto error_common;

error_authorization:
    oss << "User not authorized to perform this operation.";
    goto error_common;

error_filter_flag:
    oss << "Incorrect filter_flag, must be >= -2.";
    goto error_common;

error_dump:
    oss << "Error getting virtual network pool";
    goto error_common;

error_common:

    arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
    arrayData.push_back(xmlrpc_c::value_string(oss.str()));

    NebulaLog::log("ReM",Log::ERROR,oss);

    xmlrpc_c::value_array arrayresult_error(arrayData);

    *retval = arrayresult_error;

    return;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<|endoftext|>


<commit_before>/*
    Copyright 2002-2013 CEA LIST

    This file is part of LIMA.

    LIMA is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    LIMA 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/
#include "AmosePluginsManager.h"
#include "common/LimaCommon.h"
#include "common/AbstractFactoryPattern/DynamicLibrariesManager.h"

#include <iostream>
#include <QFile>
#include <QDir>

using namespace Lima;
using namespace Lima::Common;

AmosePluginsManager::AmosePluginsManager()
{
  loadPlugins();
}

bool AmosePluginsManager::loadPlugins()
{
  ABSTRACTFACTORYPATTERNLOGINIT;
  LINFO << "AmosePluginsManager::loadPlugins";
//   DynamicLibrariesManager::changeable().addSearchPath("c:\amose\lib");;
  // open LIMA_CONF/plugins file
  QDir pluginsDir(QString::fromUtf8(qgetenv("LIMA_CONF").constData()==0?"":qgetenv("LIMA_CONF").constData()) + "/plugins");
  QStringList pluginsFiles = pluginsDir.entryList(QDir::Files);
  Q_FOREACH(QString pluginsFile, pluginsFiles)
  {
    LINFO << "AmosePluginsManager::loadPlugins loding plugins file " << pluginsFile.toUtf8().data();
    QFile file(pluginsDir.path() + "/" + pluginsFile);
    if (!file.open(QIODevice::ReadOnly))
      return false;
    // for each entry, call load library
    while (!file.atEnd())
    {
      QByteArray line = file.readLine();
      if (line.endsWith('\n')) line.chop(1);
      // Allows empty and comment lines
      if ( !line.isEmpty() && !line.startsWith('#') )
      {
#ifdef WIN32
        QString strline = QString(line.data()).trimmed() + ".dll";
        QString library_path=QString::fromUtf8(qgetenv("LD_LIBRARY_PATH").constData()==0?"c:\amose\lib":qgetenv("LD_LIBRARY_PATH").constData());
        DynamicLibrariesManager::changeable().addSearchPathes( library_path.toUtf8().data());
#else
        QString strline = QString("lib") + line.data() + ".so";
#endif
        LDEBUG << "AmosePluginsManager::loadPlugins loading plugin '" << strline.toUtf8().data() << "'";
        std::cout << "AmosePluginsManager::loadPlugins loading plugin '" << strline.toUtf8().data() << "'"<<std::endl;
        DynamicLibrariesManager::changeable().loadLibrary(strline.toUtf8().data());
      }
    }
  }
  return true;
}
<commit_msg>remove verbose logs<commit_after>/*
    Copyright 2002-2013 CEA LIST

    This file is part of LIMA.

    LIMA is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    LIMA 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/
#include "AmosePluginsManager.h"
#include "common/LimaCommon.h"
#include "common/AbstractFactoryPattern/DynamicLibrariesManager.h"

#include <iostream>
#include <QFile>
#include <QDir>

using namespace Lima;
using namespace Lima::Common;

AmosePluginsManager::AmosePluginsManager()
{
  loadPlugins();
}

bool AmosePluginsManager::loadPlugins()
{
  ABSTRACTFACTORYPATTERNLOGINIT;
  LINFO << "AmosePluginsManager::loadPlugins";
//   DynamicLibrariesManager::changeable().addSearchPath("c:\amose\lib");;
  // open LIMA_CONF/plugins file
  QDir pluginsDir(QString::fromUtf8(qgetenv("LIMA_CONF").constData()==0?"":qgetenv("LIMA_CONF").constData()) + "/plugins");
  QStringList pluginsFiles = pluginsDir.entryList(QDir::Files);
  Q_FOREACH(QString pluginsFile, pluginsFiles)
  {
    LINFO << "AmosePluginsManager::loadPlugins loding plugins file " << pluginsFile.toUtf8().data();
    QFile file(pluginsDir.path() + "/" + pluginsFile);
    if (!file.open(QIODevice::ReadOnly))
      return false;
    // for each entry, call load library
    while (!file.atEnd())
    {
      QByteArray line = file.readLine();
      if (line.endsWith('\n')) line.chop(1);
      // Allows empty and comment lines
      if ( !line.isEmpty() && !line.startsWith('#') )
      {
#ifdef WIN32
        QString strline = QString(line.data()).trimmed() + ".dll";
        QString library_path=QString::fromUtf8(qgetenv("LD_LIBRARY_PATH").constData()==0?"c:\amose\lib":qgetenv("LD_LIBRARY_PATH").constData());
        DynamicLibrariesManager::changeable().addSearchPathes( library_path.toUtf8().data());
#else
        QString strline = QString("lib") + line.data() + ".so";
#endif
#ifdef DEBUG_CD
        LDEBUG << "AmosePluginsManager::loadPlugins loading plugin '" << strline.toUtf8().data() << "'";
#endif
        DynamicLibrariesManager::changeable().loadLibrary(strline.toUtf8().data());
      }
    }
  }
  return true;
}
<|endoftext|>


<commit_before>#include "condor_common.h"
#include <sys/socket.h>
#include <netinet/in.h>

#if !defined(LINUX) && !defined(HPUX9)
#include <sys/select.h>
#endif

#include "condor_types.h"
#include "condor_debug.h"
#include "condor_expressions.h"
#include "condor_mach_status.h"
#include "condor_attributes.h"
#include "sched.h"

#include "event.h"
#include "state.h"
#include "resource.h"
#include "resmgr.h"

extern ClassAd* template_ClassAd;

static char *_FileName_ = __FILE__;

/*
 * Higher level routines to manage a collection of resources.
 * XXX - DON'T do this using lineair searches..
 */

static resource_info_t *resources=NULL;
static int nresources;
static fd_set cur_fds;

static int resmgr_vacateone(resource_info_t *);
static int resmgr_addfd(resource_info_t *);
static int resmgr_command(resource_info_t *);
void update_central_mgr(void);

extern "C" int resmgr_setsocks(fd_set* fds);
extern "C" int resmgr_call(fd_set* fds);
extern "C" void resmgr_changestate(resource_id_t rid, int new_state);

// collect all resources that were listed in the config file
// initialize(including the ClassAd in each resource)
//  and store them in the global resources array. The number
// of such resources (just 1 if RESOURCE_LIST i snot specified
// in the config \file is recorded by nresources.
int resmgr_init()
{
	int nres, i, index;
	resource_name_t *rnames;
	resource_id_t rid;
	resource_param_t param;

	// collect all resources that were listed in the config file
	// and their number
	resource_names(&rnames, &nres);
	dprintf(D_ALWAYS, "resmgr_init: %d resources.\n", nres);
	resources = (resource_info_t *)calloc(nres, (sizeof (resource_info_t)));
	for (i = index = 0; i < nres; i++) {
		dprintf(D_ALWAYS, "opening resource '%s'\n", rnames[i]);
		if (resource_open(rnames[i], &rid) < 0)
			continue;
		resources[index].r_rid = rid;
		dprintf(D_ALWAYS, "resource %d has id '%s'\n", index,
			resources[index].r_rid);
		resources[index].r_state = NO_JOB;
		if (resource_timeout_params(rid, NO_JID, NO_TID,
		    &resources[index].r_param, NULL) < 0)
			continue;
		if (resource_update_params(rid, NO_JID, NO_TID,
		    &resources[index].r_param, NULL) < 0)
			continue;
		resources[index].r_name = rnames[i];
		resources[index].r_pid = NO_PID;
		resources[index].r_claimed = FALSE;
		// C H A N G E -> N Anand
		resources[index].r_classad = new ClassAd(*template_ClassAd);
		resources[index].r_jobclassad = NULL;
		resources[index].r_capab = NULL;
		resources[index].r_interval = 0;
		resources[index].r_receivetime = 0;
		resources[index].r_universe = STANDARD;
		dprintf(D_FULLDEBUG, "create_classad returned %x\n",
			resources[index].r_classad);
		resources[index].r_port = create_port(&resources[index].r_sock);
		// CHANGE -> N Anand
		resource_initAd(&resources[index]);
		/* XXX following must be last in this initialization */
		resource_timeout_classad(&resources[index]);
		resource_update_classad(&resources[index]);
		index++;
	}
	nresources = index;
	dprintf(D_ALWAYS, "nresources set to %d\n", nresources);
	return 0;
}

int
resmgr_setsocks(fd_set* fds)
{
	FD_ZERO(&cur_fds);
	resmgr_walk(resmgr_addfd);
	*fds = cur_fds;
	return 0;
}

int
resmgr_call(fd_set* fds)
{
	cur_fds = *fds;
	return resmgr_walk(resmgr_command);
}

int
resmgr_add(resource_id_t rid, resource_info_t* rinfop)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (resource_isused(resources[i])) {
			resources[i] = *rinfop;
			break;
		}
	}
	return i == nresources ? -1 : 0;
}

int
resmgr_del(resource_id_t rid)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (!resource_isused(resources[i]))
			continue;
		if (!resource_ridcmp(resources[i].r_rid, rid)) {
			resource_markunused(resources[i]);
			break;
		}
	}
	return i == nresources ? -1 : 0;
}

resource_info_t *
resmgr_getbyrid(resource_id_t rid)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (!resource_ridcmp(resources[i].r_rid, rid))
			return &resources[i];
	}
	return (resource_info_t *)0;
}

resource_info_t *
resmgr_getbyname(resource_name_t rname)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (!resource_rnamecmp(resources[i].r_name, rname))
			return &resources[i];
	}
	return (resource_info_t *)0;
}

resource_info_t *
resmgr_getbypid(int pid)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (resources[i].r_pid == pid)
			return &resources[i];
	}
	return (resource_info_t *)0;
}

int
resmgr_walk(int (*func)(resource_info_t*))
{
	int i;

	for (i = 0; i < nresources; i++)
		func(&resources[i]);
	return 0;
}

int
resmgr_vacateall(void)
{
	return resmgr_walk(resmgr_vacateone);
}

bool
resmgr_resourceinuse(void)
{
	int i;

	for (i = 0; i < nresources; i++)
		if (resources[i].r_state != NO_JOB) return true;
	return false;
}

static int
resmgr_vacateone(resource_info_t* rinfop)
{
	resource_id_t rid;

	rid = rinfop->r_rid;
	return resource_event(rid, NO_JID, NO_TID, EV_VACATE);
}

static int
resmgr_addfd(resource_info_t* rip)
{
	FD_SET(rip->r_sock, &cur_fds);
	return 0;
}

static int
resmgr_command(resource_info_t* rinfop)
{
	if (FD_ISSET(rinfop->r_sock, &cur_fds)) {
		call_incoming(rinfop->r_sock, SOCK_STREAM, rinfop->r_rid);
		FD_CLR(rinfop->r_sock , &cur_fds);
	}
	return 0;
}

ClassAd*
resmgr_classad(resource_id_t rid)
{
	resource_info_t *rip;

	if (!(rip = resmgr_getbyrid(rid)))
		return NULL;

	return rip->r_classad;
}

char *
state_to_string(int state)
{
	switch (state) {
	case NO_JOB:
		return "NoJob";
	case JOB_RUNNING:
		return "Running";
	case KILLED:
		return "Killed";
	case CHECKPOINTING:
		return "Checkpointing";
	case SUSPENDED:
		return "Suspended";
	case BLOCKED:
		return "Blocked";
	case SYSTEM:
		return "System";
	}
	return "Unknown";
}

void resmgr_changestate(resource_id_t rid, int new_state)
{
  ClassAd* cp;
  char *name;
  char tmp[80];
  int start = FALSE;
  int claimed;
  resource_info_t *rip;

  if (!(rip = resmgr_getbyrid(rid)))
    return;

  cp = rip->r_classad;
  claimed = rip->r_claimed;

  switch (new_state)
  {
   case NO_JOB:
    cp->EvalBool(ATTR_REQUIREMENTS, template_ClassAd, start);
    if(start && claimed == FALSE )
    {
      set_machine_status(M_IDLE);
    }
    else
    {
      set_machine_status(USER_BUSY);
    }
    cp->Delete("ClientMachine");
    cp->Delete("RemoteUser");
    cp->Delete("JobId");
    cp->Delete("JobStart");
  case JOB_RUNNING:
    set_machine_status(JOB_RUNNING);
    break;
  case KILLED:
    set_machine_status(KILLED);
    break;
  case CHECKPOINTING:
    set_machine_status(CHECKPOINTING);
    break;
  case SUSPENDED:
    set_machine_status(SUSPENDED);
    break;
  case BLOCKED:
    set_machine_status(BLOCKED);
    break;
  case SYSTEM:
    set_machine_status(SYSTEM);
    break;
  default:
    EXCEPT("Change states, unknown state (%d)", new_state);
 }

  name = state_to_string(new_state);
  rip->r_state = new_state;

  sprintf(tmp,"State=\"%s\"",name);
  cp->InsertOrUpdate(tmp);

  sprintf(tmp,"EnteredCurrentState=%d",(int)time((time_t*)0));
  cp->InsertOrUpdate(tmp);

  update_central_mgr();
}
<commit_msg>Minor code cleaning to conform to Condor Coding Style.<commit_after>#include "condor_common.h"
#include <sys/socket.h>
#include <netinet/in.h>

#if !defined(LINUX) && !defined(HPUX9)
#include <sys/select.h>
#endif

#include "condor_types.h"
#include "condor_debug.h"
#include "condor_expressions.h"
#include "condor_mach_status.h"
#include "condor_attributes.h"
#include "sched.h"

#include "event.h"
#include "state.h"
#include "resource.h"
#include "resmgr.h"

extern ClassAd* template_ClassAd;

static char *_FileName_ = __FILE__;

/*
 * Higher level routines to manage a collection of resources.
 * XXX - DON'T do this using lineair searches..
 */

static resource_info_t *resources=NULL;
static int nresources;
static fd_set cur_fds;

static int resmgr_vacateone(resource_info_t *);
static int resmgr_addfd(resource_info_t *);
static int resmgr_command(resource_info_t *);
void update_central_mgr(void);

extern "C" int resmgr_setsocks(fd_set* fds);
extern "C" int resmgr_call(fd_set* fds);
extern "C" void resmgr_changestate(resource_id_t rid, int new_state);

// collect all resources that were listed in the config file
// initialize(including the ClassAd in each resource)
//  and store them in the global resources array. The number
// of such resources (just 1 if RESOURCE_LIST i snot specified
// in the config \file is recorded by nresources.
int resmgr_init()
{
	int nres, i, index;
	resource_name_t *rnames;
	resource_id_t rid;
	resource_param_t param;

	// collect all resources that were listed in the config file
	// and their number
	resource_names(&rnames, &nres);
	dprintf(D_ALWAYS, "resmgr_init: %d resources.\n", nres);
	resources = (resource_info_t *)calloc(nres, (sizeof (resource_info_t)));
	for (i = index = 0; i < nres; i++) {
		dprintf(D_ALWAYS, "opening resource '%s'\n", rnames[i]);
		if (resource_open(rnames[i], &rid) < 0)
			continue;
		resources[index].r_rid = rid;
		dprintf(D_ALWAYS, "resource %d has id '%s'\n", index,
			resources[index].r_rid);
		resources[index].r_state = NO_JOB;
		if (resource_timeout_params(rid, NO_JID, NO_TID,
		    &resources[index].r_param, NULL) < 0)
			continue;
		if (resource_update_params(rid, NO_JID, NO_TID,
		    &resources[index].r_param, NULL) < 0)
			continue;
		resources[index].r_name = rnames[i];
		resources[index].r_pid = NO_PID;
		resources[index].r_claimed = FALSE;
		// C H A N G E -> N Anand
		resources[index].r_classad = new ClassAd(*template_ClassAd);
		resources[index].r_jobclassad = NULL;
		resources[index].r_capab = NULL;
		resources[index].r_interval = 0;
		resources[index].r_receivetime = 0;
		resources[index].r_universe = STANDARD;
		dprintf(D_FULLDEBUG, "create_classad returned %x\n",
			resources[index].r_classad);
		resources[index].r_port = create_port(&resources[index].r_sock);
		// CHANGE -> N Anand
		resource_initAd(&resources[index]);
		/* XXX following must be last in this initialization */
		resource_timeout_classad(&resources[index]);
		resource_update_classad(&resources[index]);
		index++;
	}
	nresources = index;
	dprintf(D_ALWAYS, "nresources set to %d\n", nresources);
	return 0;
}

int
resmgr_setsocks(fd_set* fds)
{
	FD_ZERO(&cur_fds);
	resmgr_walk(resmgr_addfd);
	*fds = cur_fds;
	return 0;
}

int
resmgr_call(fd_set* fds)
{
	cur_fds = *fds;
	return resmgr_walk(resmgr_command);
}

int
resmgr_add(resource_id_t rid, resource_info_t* rinfop)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (resource_isused(resources[i])) {
			resources[i] = *rinfop;
			break;
		}
	}
	return i == nresources ? -1 : 0;
}

int
resmgr_del(resource_id_t rid)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (!resource_isused(resources[i]))
			continue;
		if (!resource_ridcmp(resources[i].r_rid, rid)) {
			resource_markunused(resources[i]);
			break;
		}
	}
	return i == nresources ? -1 : 0;
}

resource_info_t *
resmgr_getbyrid(resource_id_t rid)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (!resource_ridcmp(resources[i].r_rid, rid))
			return &resources[i];
	}
	return (resource_info_t *)0;
}

resource_info_t *
resmgr_getbyname(resource_name_t rname)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if( !resource_rnamecmp(resources[i].r_name, rname) ) {
			return &resources[i];
		}
	}
	return (resource_info_t *)0;
}

resource_info_t *
resmgr_getbypid(int pid)
{
	int i;

	for (i = 0; i < nresources; i++) {
		if (resources[i].r_pid == pid) {
			return &resources[i];
		}
	}
	return (resource_info_t *)0;
}

int
resmgr_walk(int (*func)(resource_info_t*))
{
	int i;

	for (i = 0; i < nresources; i++) {
		func(&resources[i]);
	}
	return 0;
}

int
resmgr_vacateall(void)
{
	return resmgr_walk(resmgr_vacateone);
}

bool
resmgr_resourceinuse(void)
{
	int i;
	for (i = 0; i < nresources; i++) {
		if (resources[i].r_state != NO_JOB) {
			return true;
		}
	}
	return false;
}

static int
resmgr_vacateone(resource_info_t* rinfop)
{
	resource_id_t rid;

	rid = rinfop->r_rid;
	return resource_event(rid, NO_JID, NO_TID, EV_VACATE);
}

static int
resmgr_addfd(resource_info_t* rip)
{
	FD_SET(rip->r_sock, &cur_fds);
	return 0;
}

static int
resmgr_command(resource_info_t* rinfop)
{
	if (FD_ISSET(rinfop->r_sock, &cur_fds)) {
		call_incoming(rinfop->r_sock, SOCK_STREAM, rinfop->r_rid);
		FD_CLR(rinfop->r_sock , &cur_fds);
	}
	return 0;
}

ClassAd*
resmgr_classad(resource_id_t rid)
{
	resource_info_t *rip;

	if (!(rip = resmgr_getbyrid(rid)))
		return NULL;

	return rip->r_classad;
}

char *
state_to_string(int state)
{
	switch (state) {
	case NO_JOB:
		return "NoJob";
	case JOB_RUNNING:
		return "Running";
	case KILLED:
		return "Killed";
	case CHECKPOINTING:
		return "Checkpointing";
	case SUSPENDED:
		return "Suspended";
	case BLOCKED:
		return "Blocked";
	case SYSTEM:
		return "System";
	}
	return "Unknown";
}

void resmgr_changestate(resource_id_t rid, int new_state)
{
  ClassAd* cp;
  char *name;
  char tmp[80];
  int start = FALSE;
  int claimed;
  resource_info_t *rip;

  if (!(rip = resmgr_getbyrid(rid)))
    return;

  cp = rip->r_classad;
  claimed = rip->r_claimed;

  switch (new_state) {
  case NO_JOB:
	  cp->EvalBool(ATTR_REQUIREMENTS, template_ClassAd, start);
	  if(start && claimed == FALSE ) {
		  set_machine_status(M_IDLE);
	  } else {
		  set_machine_status(USER_BUSY);
	  }
	  cp->Delete("ClientMachine");
	  cp->Delete("RemoteUser");
	  cp->Delete("JobId");
	  cp->Delete("JobStart");
  case JOB_RUNNING:
	  set_machine_status(JOB_RUNNING);
	  break;
  case KILLED:
	  set_machine_status(KILLED);
	  break;
  case CHECKPOINTING:
	  set_machine_status(CHECKPOINTING);
	  break;
  case SUSPENDED:
	  set_machine_status(SUSPENDED);
	  break;
  case BLOCKED:
	  set_machine_status(BLOCKED);
	  break;
  case SYSTEM:
	  set_machine_status(SYSTEM);
	  break;
  default:
	  EXCEPT("Change states, unknown state (%d)", new_state);
  }

  name = state_to_string(new_state);
  rip->r_state = new_state;

  sprintf(tmp,"State=\"%s\"",name);
  cp->InsertOrUpdate(tmp);

  sprintf(tmp,"EnteredCurrentState=%d",(int)time((time_t*)0));
  cp->InsertOrUpdate(tmp);

  update_central_mgr();
}
<|endoftext|>


<commit_before>/*
 * ConsoleBuffer.cpp
 *
 *  Created on: Jul 15, 2013
 *      Author: drom
 */

#include <console/ConsoleBuffer.h>
#include <GL/gl.h>
#include <outputers/IOutputer.h>
#include <outputers/QTextOutputer.h>
#include <cstddef>
#include <deque>
#include <new>
#include <string>

ConsoleBuffer::ConsoleBuffer(unsigned maxSize) {
  this->outputer = new QTextOutputer(-20);
  this->maxSize = maxSize;
}

ConsoleBuffer::~ConsoleBuffer() {
  for(size_t i = 0; i < lines.size(); ++i) {
    delete lines[i];
  }
}

string* ConsoleBuffer::getCurrentLine() {
  if(lines.empty()) {
    newLine();
  }

  return lines.back();
}

void ConsoleBuffer::newLine() {
  lines.push_back(new string());

  if(lines.size() > maxSize) {
    delete lines.front();
    lines.pop_front();
  }
}

void ConsoleBuffer::deleteForwardFromCurrentLine() {
  // TODO This makes no sense right now, so do nothing!
}

void ConsoleBuffer::deleteBackwardFromCurrentLine() {
  string* line = getCurrentLine();
  if(line->size() > 0) {
    line->erase(line->size() - 1);
  }
}

void ConsoleBuffer::output(GLfloat x, GLfloat y, GLfloat width, GLfloat height) {
  outputer->move(x, y);
  for(size_t i = 0; i < lines.size(); ++i) {
    outputer->output(i, lines[i]);
  }
}

void ConsoleBuffer::addToEndOfCurrentLine(char input) {
  (*getCurrentLine()) += input;
}
<commit_msg>Render a cursor at the end of the current input line<commit_after>/*
 * ConsoleBuffer.cpp
 *
 *  Created on: Jul 15, 2013
 *      Author: drom
 */

#include <console/ConsoleBuffer.h>
#include <GL/gl.h>
#include <outputers/IOutputer.h>
#include <outputers/QTextOutputer.h>
#include <cstddef>
#include <deque>
#include <new>
#include <string>

ConsoleBuffer::ConsoleBuffer(unsigned maxSize) {
  this->outputer = new QTextOutputer(-20);
  this->maxSize = maxSize;
}

ConsoleBuffer::~ConsoleBuffer() {
  for(size_t i = 0; i < lines.size(); ++i) {
    delete lines[i];
  }
}

string* ConsoleBuffer::getCurrentLine() {
  if(lines.empty()) {
    newLine();
  }

  return lines.back();
}

void ConsoleBuffer::newLine() {
  lines.push_back(new string());

  if(lines.size() > maxSize) {
    delete lines.front();
    lines.pop_front();
  }
}

void ConsoleBuffer::deleteForwardFromCurrentLine() {
  // TODO This makes no sense right now, so do nothing!
}

void ConsoleBuffer::deleteBackwardFromCurrentLine() {
  string* line = getCurrentLine();
  if(line->size() > 0) {
    line->erase(line->size() - 1);
  }
}

void ConsoleBuffer::output(GLfloat x, GLfloat y, GLfloat width, GLfloat height) {
  outputer->move(x, y);

  // Render all but the active line
  for(size_t i = 0; i + 1 < lines.size(); ++i) {
    outputer->output(i, lines[i]);
  }

  // Render the active line with a cursor at the end
  // TODO Allow cursor to be moved w/in the line
  string currentLineForOutput = *getCurrentLine() + string("_");
  outputer->output(lines.size() - 1, &currentLineForOutput);
}

void ConsoleBuffer::addToEndOfCurrentLine(char input) {
  (*getCurrentLine()) += input;
}
<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2011 J-P Nurmi jpnurmi@gmail.com
*
* 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.
*/

#include "completer.h"
#include "historylineedit.h"

Completer::Completer(QObject* parent) : QCompleter(parent)
{
    d.lineEdit = 0;
    d.defaultModel = 0;
    d.slashModel = 0;
    setCaseSensitivity(Qt::CaseInsensitive);
    setCompletionMode(InlineCompletion);
    connect(this, SIGNAL(highlighted(QString)), this, SLOT(insertCompletion(QString)));
}

HistoryLineEdit* Completer::lineEdit() const
{
    return d.lineEdit;
}

void Completer::setLineEdit(HistoryLineEdit* lineEdit)
{
    if (d.lineEdit != lineEdit)
    {
        if (d.lineEdit)
            disconnect(d.lineEdit, SIGNAL(textEdited(QString)), this, SLOT(onTextEdited()));

        if (lineEdit)
            connect(lineEdit, SIGNAL(textEdited(QString)), this, SLOT(onTextEdited()));

        d.lineEdit = lineEdit;
    }
}

QAbstractItemModel* Completer::defaultModel() const
{
    return d.defaultModel;
}

void Completer::setDefaultModel(QAbstractItemModel* model)
{
    d.defaultModel = model;
}

QAbstractItemModel* Completer::slashModel() const
{
    return d.slashModel;
}

void Completer::setSlashModel(QAbstractItemModel* model)
{
    d.slashModel = model;
}

void Completer::onTabPressed()
{
    if (!d.lineEdit)
        return;

    // store selection
    int pos = d.lineEdit->cursorPosition();
    int start = d.lineEdit->selectionStart();
    QString selected = d.lineEdit->selectedText();

    // select current word
    d.lineEdit->cursorWordForward(false);
    d.lineEdit->cursorWordBackward(true);
    QString word = d.lineEdit->selectedText();

    // choose model
    if (word.startsWith('/'))
        setModel(d.slashModel);
    else
        setModel(d.defaultModel);

    QString prefix = completionPrefix();
    if (prefix.isEmpty() || !word.startsWith(prefix, Qt::CaseInsensitive))
        setCompletionPrefix(word);

    // restore selection
    d.lineEdit->setCursorPosition(pos);
    if (start != -1)
        d.lineEdit->setSelection(start, selected.length());

    // complete
    if (!word.isEmpty())
    {
        complete();

        int count = completionCount();
        if (count > 0)
        {
            int next = currentRow() + 1;
            setCurrentRow(next % count);
        }
    }
}

void Completer::onTextEdited()
{
    setCompletionPrefix(QString());
}

void Completer::insertCompletion(const QString& completion)
{
    if (!d.lineEdit)
        return;

    int pos = d.lineEdit->cursorPosition();
    QString text = d.lineEdit->text();
    if (pos > 0 && pos < text.length() && !text.at(pos - 1).isSpace())
        d.lineEdit->cursorWordForward(false);
    d.lineEdit->cursorWordBackward(true);
    pos = d.lineEdit->cursorPosition();

    QString tmp = completion;
    if (pos == 0 && !completion.startsWith("/"))
        tmp.append(":");
    d.lineEdit->insert(tmp);

    text = d.lineEdit->text();
    int cursor = d.lineEdit->cursorPosition();
    if (!text.at(cursor - 1).isSpace())
        d.lineEdit->insert(" ");
}
<commit_msg>Fixed nick completion<commit_after>/*
* Copyright (C) 2008-2011 J-P Nurmi jpnurmi@gmail.com
*
* 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.
*/

#include "completer.h"
#include "historylineedit.h"

Completer::Completer(QObject* parent) : QCompleter(parent)
{
    d.lineEdit = 0;
    d.defaultModel = 0;
    d.slashModel = 0;
    setCaseSensitivity(Qt::CaseInsensitive);
    setCompletionMode(InlineCompletion);
    connect(this, SIGNAL(highlighted(QString)), this, SLOT(insertCompletion(QString)));
}

HistoryLineEdit* Completer::lineEdit() const
{
    return d.lineEdit;
}

void Completer::setLineEdit(HistoryLineEdit* lineEdit)
{
    if (d.lineEdit != lineEdit)
    {
        if (d.lineEdit)
            disconnect(d.lineEdit, SIGNAL(textEdited(QString)), this, SLOT(onTextEdited()));

        if (lineEdit)
            connect(lineEdit, SIGNAL(textEdited(QString)), this, SLOT(onTextEdited()));

        d.lineEdit = lineEdit;
    }
}

QAbstractItemModel* Completer::defaultModel() const
{
    return d.defaultModel;
}

void Completer::setDefaultModel(QAbstractItemModel* model)
{
    d.defaultModel = model;
}

QAbstractItemModel* Completer::slashModel() const
{
    return d.slashModel;
}

void Completer::setSlashModel(QAbstractItemModel* model)
{
    d.slashModel = model;
}

void Completer::onTabPressed()
{
    if (!d.lineEdit)
        return;

    // store selection
    int pos = d.lineEdit->cursorPosition();
    int start = d.lineEdit->selectionStart();
    QString selected = d.lineEdit->selectedText();

    // select current word
    d.lineEdit->cursorWordForward(false);
    d.lineEdit->cursorWordBackward(true);
    QString word = d.lineEdit->selectedText();

    // choose model
    if (word.startsWith('/'))
    {
        if (model() != d.slashModel)
            setModel(d.slashModel);
    }
    else
    {
        if (model() != d.defaultModel)
            setModel(d.defaultModel);
    }

    QString prefix = completionPrefix();
    if (prefix.isEmpty() || !word.startsWith(prefix, Qt::CaseInsensitive))
        setCompletionPrefix(word);

    // restore selection
    d.lineEdit->setCursorPosition(pos);
    if (start != -1)
        d.lineEdit->setSelection(start, selected.length());

    // complete
    if (!word.isEmpty())
    {
        complete();

        int count = completionCount();
        if (count > 0)
        {
            int next = currentRow() + 1;
            setCurrentRow(next % count);
        }
    }
}

void Completer::onTextEdited()
{
    setCompletionPrefix(QString());
}

void Completer::insertCompletion(const QString& completion)
{
    if (!d.lineEdit)
        return;

    int pos = d.lineEdit->cursorPosition();
    QString text = d.lineEdit->text();
    if (pos > 0 && pos < text.length() && !text.at(pos - 1).isSpace())
        d.lineEdit->cursorWordForward(false);
    d.lineEdit->cursorWordBackward(true);
    pos = d.lineEdit->cursorPosition();

    QString tmp = completion;
    if (pos == 0 && !completion.startsWith("/"))
        tmp.append(":");
    d.lineEdit->insert(tmp);

    text = d.lineEdit->text();
    int cursor = d.lineEdit->cursorPosition();
    if (!text.at(cursor - 1).isSpace())
        d.lineEdit->insert(" ");
}
<|endoftext|>


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

/**
 * @file cartesian_frenet_conversion.cc
 **/

#include "modules/planning/math/frame_conversion/cartesian_frenet_conversion.h"

#include <cmath>

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"

namespace apollo {
namespace planning {

using apollo::common::math::Vec2d;

void CartesianFrenetConverter::cartesian_to_frenet(
    const double rs, const double rx, const double ry, const double rtheta,
    const double rkappa, const double rdkappa, const double x, const double y,
    const double v, const double a, const double theta, const double kappa,
    std::array<double, 3>* const ptr_s_condition,
    std::array<double, 3>* const ptr_d_condition) {
  const double dx = x - rx;
  const double dy = y - ry;

  const double cos_theta_r = std::cos(rtheta);
  const double sin_theta_r = std::sin(rtheta);

  const double cross_rd_nd = cos_theta_r * dy - sin_theta_r * dx;
  ptr_d_condition->at(0) =
      std::copysign(std::sqrt(dx * dx + dy * dy), cross_rd_nd);

  const double delta_theta = theta - rtheta;
  const double tan_delta_theta = std::tan(delta_theta);
  const double cos_delta_theta = std::cos(delta_theta);

  const double one_minus_kappa_r_d = 1 - rkappa * ptr_d_condition->at(0);
  ptr_d_condition->at(1) = one_minus_kappa_r_d * tan_delta_theta;

  const double kappa_r_d_prime =
      rdkappa * ptr_d_condition->at(0) + rkappa * ptr_d_condition->at(1);

  ptr_d_condition->at(2) =
      -kappa_r_d_prime * tan_delta_theta +
      one_minus_kappa_r_d / cos_delta_theta / cos_delta_theta *
          (kappa * one_minus_kappa_r_d / cos_delta_theta - rkappa);

  ptr_s_condition->at(0) = rs;

  ptr_s_condition->at(1) = v * cos_delta_theta / one_minus_kappa_r_d;

  const double delta_theta_prime =
      one_minus_kappa_r_d / cos_delta_theta * kappa - rkappa;
  ptr_s_condition->at(2) =
      (a * cos_delta_theta -
       ptr_s_condition->at(1) * ptr_s_condition->at(1) *
           (ptr_d_condition->at(1) * delta_theta_prime - kappa_r_d_prime)) /
      one_minus_kappa_r_d;
  return;
}

void CartesianFrenetConverter::frenet_to_cartesian(
    const double rs, const double rx, const double ry, const double rtheta,
    const double rkappa, const double rdkappa,
    const std::array<double, 3>& s_condition,
    const std::array<double, 3>& d_condition, double* const ptr_x,
    double* const ptr_y, double* const ptr_theta, double* const ptr_kappa,
    double* const ptr_v, double* const ptr_a) {
  CHECK(std::abs(rs - s_condition[0]) < 1.0e-6 &&
        "The reference point s and s_condition[0] don't match");

  const double cos_theta_r = std::cos(rtheta);
  const double sin_theta_r = std::sin(rtheta);

  *ptr_x = rx - sin_theta_r * d_condition[0];
  *ptr_y = ry + cos_theta_r * d_condition[0];

  const double one_minus_kappa_r_d = 1 - rkappa * d_condition[0];

  const double tan_delta_theta = d_condition[1] / one_minus_kappa_r_d;
  const double delta_theta = std::atan2(d_condition[1], one_minus_kappa_r_d);
  const double cos_delta_theta = std::cos(delta_theta);

  *ptr_theta = common::math::NormalizeAngle(delta_theta + rtheta);

  const double kappa_r_d_prime =
      rdkappa * d_condition[0] + rkappa * d_condition[1];
  *ptr_kappa = (((d_condition[2] + kappa_r_d_prime * tan_delta_theta) *
                 cos_delta_theta * cos_delta_theta) /
                    (one_minus_kappa_r_d) +
                rkappa) *
               cos_delta_theta / (one_minus_kappa_r_d);

  const double d_dot = d_condition[1] * s_condition[1];
  *ptr_v = std::sqrt(one_minus_kappa_r_d * one_minus_kappa_r_d *
                         s_condition[1] * s_condition[1] +
                     d_dot * d_dot);

  const double delta_theta_prime =
      one_minus_kappa_r_d / cos_delta_theta * (*ptr_kappa) - rkappa;

  *ptr_a = s_condition[2] * one_minus_kappa_r_d / cos_delta_theta +
           s_condition[1] * s_condition[1] / cos_delta_theta *
               (d_condition[1] * delta_theta_prime - kappa_r_d_prime);
}

double CartesianFrenetConverter::CalculateTheta(const double rtheta,
                                                const double rkappa,
                                                const double l,
                                                const double dl) {
  return common::math::NormalizeAngle(rtheta + std::atan2(dl, 1 - l * rkappa));
}

double CartesianFrenetConverter::CalculateKappa(const double rkappa,
                                                const double rdkappa,
                                                const double l, const double dl,
                                                const double ddl) {
  double denominator = (dl * dl + (1 - l * rkappa) * (1 - l * rkappa));
  if (std::fabs(denominator) < 1e-8) {
    return 0.0;
  }
  denominator = std::pow(denominator, 1.5);
  const double numerator = rkappa + ddl - 2 * l * rkappa * rkappa -
                           l * ddl * rkappa + l * l * rkappa * rkappa * rkappa +
                           l * dl * rdkappa + 2 * dl * dl * rkappa;
  return numerator / denominator;
}

Vec2d CartesianFrenetConverter::CalculateCartesianPoint(const double rtheta,
                                                        const Vec2d& rpoint,
                                                        const double l) {
  const double x = rpoint.x() - l * std::sin(rtheta);
  const double y = rpoint.y() + l * std::cos(rtheta);
  return Vec2d(x, y);
}

double CartesianFrenetConverter::CalculateLateralDerivative(
    const double rtheta, const double theta, const double l,
    const double rkappa) {
  return (1 - rkappa * l) * std::tan(theta - rtheta);
}

double CartesianFrenetConverter::CalculateSecondOrderLateralDerivative(
    const double rtheta, const double theta, const double rkappa,
    const double kappa, const double rdkappa, const double l) {
  const double dl = CalculateLateralDerivative(rtheta, theta, l, rkappa);
  const double theta_diff = theta - rtheta;
  const double cos_theta_diff = std::cos(theta_diff);
  const double res = -(rdkappa * l + rkappa * dl) * std::tan(theta - rtheta) +
                     (1 - rkappa * l) / (cos_theta_diff * cos_theta_diff) *
                         (kappa * (1 - rkappa * l) / cos_theta_diff - rkappa);
  if (std::isinf(res)) {
    AWARN << "result is inf when calculate second order lateral "
             "derivative. input values are rtheta:"
          << rtheta << " theta: " << theta << ", rkappa: " << rkappa
          << ", kappa: " << kappa << ", rdkappa: " << rdkappa << ", l: " << l
          << std::endl;
  }
  return res;
}

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

/**
 * @file cartesian_frenet_conversion.cc
 **/

#include "modules/planning/math/frame_conversion/cartesian_frenet_conversion.h"

#include <cmath>

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"

namespace apollo {
namespace planning {

using apollo::common::math::Vec2d;

void CartesianFrenetConverter::cartesian_to_frenet(
    const double rs, const double rx, const double ry, const double rtheta,
    const double rkappa, const double rdkappa, const double x, const double y,
    const double v, const double a, const double theta, const double kappa,
    std::array<double, 3>* const ptr_s_condition,
    std::array<double, 3>* const ptr_d_condition) {
  const double dx = x - rx;
  const double dy = y - ry;

  const double cos_theta_r = std::cos(rtheta);
  const double sin_theta_r = std::sin(rtheta);

  const double cross_rd_nd = cos_theta_r * dy - sin_theta_r * dx;
  ptr_d_condition->at(0) =
      std::copysign(std::sqrt(dx * dx + dy * dy), cross_rd_nd);

  const double delta_theta = theta - rtheta;
  const double tan_delta_theta = std::tan(delta_theta);
  const double cos_delta_theta = std::cos(delta_theta);

  const double one_minus_kappa_r_d = 1 - rkappa * ptr_d_condition->at(0);
  ptr_d_condition->at(1) = one_minus_kappa_r_d * tan_delta_theta;

  const double kappa_r_d_prime =
      rdkappa * ptr_d_condition->at(0) + rkappa * ptr_d_condition->at(1);

  ptr_d_condition->at(2) =
      -kappa_r_d_prime * tan_delta_theta +
      one_minus_kappa_r_d / cos_delta_theta / cos_delta_theta *
          (kappa * one_minus_kappa_r_d / cos_delta_theta - rkappa);

  ptr_s_condition->at(0) = rs;

  ptr_s_condition->at(1) = v * cos_delta_theta / one_minus_kappa_r_d;

  const double delta_theta_prime =
      one_minus_kappa_r_d / cos_delta_theta * kappa - rkappa;
  ptr_s_condition->at(2) =
      (a * cos_delta_theta -
       ptr_s_condition->at(1) * ptr_s_condition->at(1) *
           (ptr_d_condition->at(1) * delta_theta_prime - kappa_r_d_prime)) /
      one_minus_kappa_r_d;
  return;
}

void CartesianFrenetConverter::frenet_to_cartesian(
    const double rs, const double rx, const double ry, const double rtheta,
    const double rkappa, const double rdkappa,
    const std::array<double, 3>& s_condition,
    const std::array<double, 3>& d_condition, double* const ptr_x,
    double* const ptr_y, double* const ptr_theta, double* const ptr_kappa,
    double* const ptr_v, double* const ptr_a) {
  CHECK(std::abs(rs - s_condition[0]) < 1.0e-6)
      << "The reference point s and s_condition[0] don't match";

  const double cos_theta_r = std::cos(rtheta);
  const double sin_theta_r = std::sin(rtheta);

  *ptr_x = rx - sin_theta_r * d_condition[0];
  *ptr_y = ry + cos_theta_r * d_condition[0];

  const double one_minus_kappa_r_d = 1 - rkappa * d_condition[0];

  const double tan_delta_theta = d_condition[1] / one_minus_kappa_r_d;
  const double delta_theta = std::atan2(d_condition[1], one_minus_kappa_r_d);
  const double cos_delta_theta = std::cos(delta_theta);

  *ptr_theta = common::math::NormalizeAngle(delta_theta + rtheta);

  const double kappa_r_d_prime =
      rdkappa * d_condition[0] + rkappa * d_condition[1];
  *ptr_kappa = (((d_condition[2] + kappa_r_d_prime * tan_delta_theta) *
                 cos_delta_theta * cos_delta_theta) /
                    (one_minus_kappa_r_d) +
                rkappa) *
               cos_delta_theta / (one_minus_kappa_r_d);

  const double d_dot = d_condition[1] * s_condition[1];
  *ptr_v = std::sqrt(one_minus_kappa_r_d * one_minus_kappa_r_d *
                         s_condition[1] * s_condition[1] +
                     d_dot * d_dot);

  const double delta_theta_prime =
      one_minus_kappa_r_d / cos_delta_theta * (*ptr_kappa) - rkappa;

  *ptr_a = s_condition[2] * one_minus_kappa_r_d / cos_delta_theta +
           s_condition[1] * s_condition[1] / cos_delta_theta *
               (d_condition[1] * delta_theta_prime - kappa_r_d_prime);
}

double CartesianFrenetConverter::CalculateTheta(const double rtheta,
                                                const double rkappa,
                                                const double l,
                                                const double dl) {
  return common::math::NormalizeAngle(rtheta + std::atan2(dl, 1 - l * rkappa));
}

double CartesianFrenetConverter::CalculateKappa(const double rkappa,
                                                const double rdkappa,
                                                const double l, const double dl,
                                                const double ddl) {
  double denominator = (dl * dl + (1 - l * rkappa) * (1 - l * rkappa));
  if (std::fabs(denominator) < 1e-8) {
    return 0.0;
  }
  denominator = std::pow(denominator, 1.5);
  const double numerator = rkappa + ddl - 2 * l * rkappa * rkappa -
                           l * ddl * rkappa + l * l * rkappa * rkappa * rkappa +
                           l * dl * rdkappa + 2 * dl * dl * rkappa;
  return numerator / denominator;
}

Vec2d CartesianFrenetConverter::CalculateCartesianPoint(const double rtheta,
                                                        const Vec2d& rpoint,
                                                        const double l) {
  const double x = rpoint.x() - l * std::sin(rtheta);
  const double y = rpoint.y() + l * std::cos(rtheta);
  return Vec2d(x, y);
}

double CartesianFrenetConverter::CalculateLateralDerivative(
    const double rtheta, const double theta, const double l,
    const double rkappa) {
  return (1 - rkappa * l) * std::tan(theta - rtheta);
}

double CartesianFrenetConverter::CalculateSecondOrderLateralDerivative(
    const double rtheta, const double theta, const double rkappa,
    const double kappa, const double rdkappa, const double l) {
  const double dl = CalculateLateralDerivative(rtheta, theta, l, rkappa);
  const double theta_diff = theta - rtheta;
  const double cos_theta_diff = std::cos(theta_diff);
  const double res = -(rdkappa * l + rkappa * dl) * std::tan(theta - rtheta) +
                     (1 - rkappa * l) / (cos_theta_diff * cos_theta_diff) *
                         (kappa * (1 - rkappa * l) / cos_theta_diff - rkappa);
  if (std::isinf(res)) {
    AWARN << "result is inf when calculate second order lateral "
             "derivative. input values are rtheta:"
          << rtheta << " theta: " << theta << ", rkappa: " << rkappa
          << ", kappa: " << kappa << ", rdkappa: " << rdkappa << ", l: " << l
          << std::endl;
  }
  return res;
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>