<commit_before>
/* Includes ------------------------------------------------------------------*/

#include "communication.h"

#include "interface_usb.h"
#include "interface_uart.h"
#include "interface_can.hpp"
#include "interface_i2c.h"

#include "odrive_main.h"
#include "freertos_vars.h"
#include "utils.h"

#include "../build/version.h" // autogenerated based on Git state

#include <cmsis_os.h>
#include <memory>
//#include <usbd_cdc_if.h>
//#include <usb_device.h>
//#include <usart.h>
#include <gpio.h>

#include <type_traits>

/* Private defines -----------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Global constant data ------------------------------------------------------*/
/* Global variables ----------------------------------------------------------*/

uint64_t serial_number;
char serial_number_str[13]; // 12 digits + null termination

/* Private constant data -----------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/

#if HW_VERSION_MAJOR == 3
// Determine start address of the OTP struct:
// The OTP is organized into 16-byte blocks.
// If the first block starts with "0xfe" we use the first block.
// If the first block starts with "0x00" and the second block starts with "0xfe",
// we use the second block. This gives the user the chance to screw up once.
// If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL).
const uint8_t* otp_ptr =
    (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE :
    (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL :
        (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL :
            (uint8_t*)(FLASH_OTP_BASE + 0x10);

// Read hardware version from OTP if available, otherwise fall back
// to software defined version.
const uint8_t hw_version_major = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR;
const uint8_t hw_version_minor = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR;
const uint8_t hw_version_variant = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE;
#else
#error "not implemented"
#endif

// the corresponding macros are defined in the autogenerated version.h
const uint8_t fw_version_major = FW_VERSION_MAJOR;
const uint8_t fw_version_minor = FW_VERSION_MINOR;
const uint8_t fw_version_revision = FW_VERSION_REVISION;
const uint8_t fw_version_unreleased = FW_VERSION_UNRELEASED; // 0 for official releases, 1 otherwise

osThreadId comm_thread;
volatile bool endpoint_list_valid = false;

static uint32_t test_property = 0;

/* Private function prototypes -----------------------------------------------*/

auto make_protocol_definitions(PWMMapping_t& mapping) {
    return make_protocol_member_list(
        make_protocol_property("endpoint", &mapping.endpoint),
        make_protocol_property("min", &mapping.min),
        make_protocol_property("max", &mapping.max)
    );
}

/* Function implementations --------------------------------------------------*/

void init_communication(void) {
    printf("hi!\r\n");

    // Start command handling thread
    osThreadDef(task_cmd_parse, communication_task, osPriorityNormal, 0, 8000 /* in 32-bit words */); // TODO: fix stack issues
    comm_thread = osThreadCreate(osThread(task_cmd_parse), NULL);

    while (!endpoint_list_valid)
        osDelay(1);
}

float oscilloscope[OSCILLOSCOPE_SIZE] = {0};
size_t oscilloscope_pos = 0;

static CAN_context can1_ctx;

// Helper class because the protocol library doesn't yet
// support non-member functions
// TODO: make this go away
class StaticFunctions {
public:
    void save_configuration_helper() { save_configuration(); }
    void erase_configuration_helper() { erase_configuration(); }
    void NVIC_SystemReset_helper() { NVIC_SystemReset(); }
    void enter_dfu_mode_helper() { enter_dfu_mode(); }
    float get_oscilloscope_val(uint32_t index) { return oscilloscope[index]; }
    float get_adc_voltage_(uint32_t gpio) { return get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); }
    int32_t test_function(int32_t delta) { static int cnt = 0; return cnt += delta; }
} static_functions;

// When adding new functions/variables to the protocol, be careful not to
// blow the communication stack. You can check comm_stack_info to see
// how much headroom you have.
static inline auto make_obj_tree() {
    return make_protocol_member_list(
        make_protocol_ro_property("vbus_voltage", &vbus_voltage),
        make_protocol_ro_property("serial_number", &serial_number),
        make_protocol_ro_property("hw_version_major", &hw_version_major),
        make_protocol_ro_property("hw_version_minor", &hw_version_minor),
        make_protocol_ro_property("hw_version_variant", &hw_version_variant),
        make_protocol_ro_property("fw_version_major", &fw_version_major),
        make_protocol_ro_property("fw_version_minor", &fw_version_minor),
        make_protocol_ro_property("fw_version_revision", &fw_version_revision),
        make_protocol_ro_property("fw_version_unreleased", &fw_version_unreleased),
        make_protocol_ro_property("user_config_loaded", const_cast<const bool *>(&user_config_loaded_)),
        make_protocol_ro_property("brake_resistor_armed", &brake_resistor_armed),
        make_protocol_object("system_stats",
            make_protocol_ro_property("uptime", &system_stats_.uptime),
            make_protocol_ro_property("min_heap_space", &system_stats_.min_heap_space),
            make_protocol_ro_property("min_stack_space_axis0", &system_stats_.min_stack_space_axis0),
            make_protocol_ro_property("min_stack_space_axis1", &system_stats_.min_stack_space_axis1),
            make_protocol_ro_property("min_stack_space_comms", &system_stats_.min_stack_space_comms),
            make_protocol_ro_property("min_stack_space_usb", &system_stats_.min_stack_space_usb),
            make_protocol_ro_property("min_stack_space_uart", &system_stats_.min_stack_space_uart),
            make_protocol_ro_property("min_stack_space_usb_irq", &system_stats_.min_stack_space_usb_irq),
            make_protocol_ro_property("min_stack_space_startup", &system_stats_.min_stack_space_startup),
            make_protocol_object("usb",
                make_protocol_ro_property("rx_cnt", &usb_stats_.rx_cnt),
                make_protocol_ro_property("tx_cnt", &usb_stats_.tx_cnt),
                make_protocol_ro_property("tx_overrun_cnt", &usb_stats_.tx_overrun_cnt)
            ),
            make_protocol_object("i2c",
                make_protocol_ro_property("addr", &i2c_stats_.addr),
                make_protocol_ro_property("addr_match_cnt", &i2c_stats_.addr_match_cnt),
                make_protocol_ro_property("rx_cnt", &i2c_stats_.rx_cnt),
                make_protocol_ro_property("error_cnt", &i2c_stats_.error_cnt)
            )
        ),
        make_protocol_object("config",
            make_protocol_property("brake_resistance", &board_config.brake_resistance),
            // TODO: changing this currently requires a reboot - fix this
            make_protocol_property("enable_uart", &board_config.enable_uart),
            make_protocol_property("enable_i2c_instead_of_can" , &board_config.enable_i2c_instead_of_can), // requires a reboot
            make_protocol_property("enable_ascii_protocol_on_usb", &board_config.enable_ascii_protocol_on_usb),
            make_protocol_property("dc_bus_undervoltage_trip_level", &board_config.dc_bus_undervoltage_trip_level),
            make_protocol_property("dc_bus_overvoltage_trip_level", &board_config.dc_bus_overvoltage_trip_level),
#if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3
            make_protocol_object("gpio1_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[0])),
            make_protocol_object("gpio2_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[1])),
            make_protocol_object("gpio3_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[2])),
#endif
            make_protocol_object("gpio4_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[3])),

            make_protocol_object("gpio3_analog_mapping", make_protocol_definitions(board_config.analog_mappings[2])),
            make_protocol_object("gpio4_analog_mapping", make_protocol_definitions(board_config.analog_mappings[3]))
            ),
        make_protocol_object("axis0", axes[0]->make_protocol_definitions()),
        make_protocol_object("axis1", axes[1]->make_protocol_definitions()),
        make_protocol_object("can", can1_ctx.make_protocol_definitions()),
        make_protocol_property("test_property", &test_property),
        make_protocol_function("test_function", static_functions, &StaticFunctions::test_function, "delta"),
        make_protocol_function("get_oscilloscope_val", static_functions, &StaticFunctions::get_oscilloscope_val, "index"),
        make_protocol_function("get_adc_voltage", static_functions, &StaticFunctions::get_adc_voltage_, "gpio"),
        make_protocol_function("save_configuration", static_functions, &StaticFunctions::save_configuration_helper),
        make_protocol_function("erase_configuration", static_functions, &StaticFunctions::erase_configuration_helper),
        make_protocol_function("reboot", static_functions, &StaticFunctions::NVIC_SystemReset_helper),
        make_protocol_function("enter_dfu_mode", static_functions, &StaticFunctions::enter_dfu_mode_helper)
    );
}

using tree_type = decltype(make_obj_tree());
uint8_t tree_buffer[sizeof(tree_type)];

// Thread to handle deffered processing of USB interrupt, and
// read commands out of the UART DMA circular buffer
void communication_task(void * ctx) {
    (void) ctx; // unused parameter

    // TODO: this is supposed to use the move constructor, but currently
    // the compiler uses the copy-constructor instead. Thus the make_obj_tree
    // ends up with a stupid stack size of around 8000 bytes. Fix this.
    auto tree_ptr = new (tree_buffer) tree_type(make_obj_tree());
    fibre_publish(*tree_ptr);

    // Allow main init to continue
    endpoint_list_valid = true;

    start_uart_server();
    start_usb_server();
    if (board_config.enable_i2c_instead_of_can) {
        start_i2c_server();
    } else {
        // TODO: finish implementing CAN
        // start_can_server(can1_ctx, CAN1, serial_number);
    }

    for (;;) {
        osDelay(1000); // nothing to do
    }
}

extern "C" {
int _write(int file, const char* data, int len);
}

// @brief This is what printf calls internally
int _write(int file, const char* data, int len) {
#ifdef USB_PROTOCOL_STDOUT
    usb_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);
#endif
#ifdef UART_PROTOCOL_STDOUT
    uart4_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);
#endif
    return len;
}
<commit_msg>add max regen current to protocl<commit_after>
/* Includes ------------------------------------------------------------------*/

#include "communication.h"

#include "interface_usb.h"
#include "interface_uart.h"
#include "interface_can.hpp"
#include "interface_i2c.h"

#include "odrive_main.h"
#include "freertos_vars.h"
#include "utils.h"

#include "../build/version.h" // autogenerated based on Git state

#include <cmsis_os.h>
#include <memory>
//#include <usbd_cdc_if.h>
//#include <usb_device.h>
//#include <usart.h>
#include <gpio.h>

#include <type_traits>

/* Private defines -----------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Global constant data ------------------------------------------------------*/
/* Global variables ----------------------------------------------------------*/

uint64_t serial_number;
char serial_number_str[13]; // 12 digits + null termination

/* Private constant data -----------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/

#if HW_VERSION_MAJOR == 3
// Determine start address of the OTP struct:
// The OTP is organized into 16-byte blocks.
// If the first block starts with "0xfe" we use the first block.
// If the first block starts with "0x00" and the second block starts with "0xfe",
// we use the second block. This gives the user the chance to screw up once.
// If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL).
const uint8_t* otp_ptr =
    (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE :
    (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL :
        (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL :
            (uint8_t*)(FLASH_OTP_BASE + 0x10);

// Read hardware version from OTP if available, otherwise fall back
// to software defined version.
const uint8_t hw_version_major = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR;
const uint8_t hw_version_minor = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR;
const uint8_t hw_version_variant = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE;
#else
#error "not implemented"
#endif

// the corresponding macros are defined in the autogenerated version.h
const uint8_t fw_version_major = FW_VERSION_MAJOR;
const uint8_t fw_version_minor = FW_VERSION_MINOR;
const uint8_t fw_version_revision = FW_VERSION_REVISION;
const uint8_t fw_version_unreleased = FW_VERSION_UNRELEASED; // 0 for official releases, 1 otherwise

osThreadId comm_thread;
volatile bool endpoint_list_valid = false;

static uint32_t test_property = 0;

/* Private function prototypes -----------------------------------------------*/

auto make_protocol_definitions(PWMMapping_t& mapping) {
    return make_protocol_member_list(
        make_protocol_property("endpoint", &mapping.endpoint),
        make_protocol_property("min", &mapping.min),
        make_protocol_property("max", &mapping.max)
    );
}

/* Function implementations --------------------------------------------------*/

void init_communication(void) {
    printf("hi!\r\n");

    // Start command handling thread
    osThreadDef(task_cmd_parse, communication_task, osPriorityNormal, 0, 8000 /* in 32-bit words */); // TODO: fix stack issues
    comm_thread = osThreadCreate(osThread(task_cmd_parse), NULL);

    while (!endpoint_list_valid)
        osDelay(1);
}

float oscilloscope[OSCILLOSCOPE_SIZE] = {0};
size_t oscilloscope_pos = 0;

static CAN_context can1_ctx;

// Helper class because the protocol library doesn't yet
// support non-member functions
// TODO: make this go away
class StaticFunctions {
public:
    void save_configuration_helper() { save_configuration(); }
    void erase_configuration_helper() { erase_configuration(); }
    void NVIC_SystemReset_helper() { NVIC_SystemReset(); }
    void enter_dfu_mode_helper() { enter_dfu_mode(); }
    float get_oscilloscope_val(uint32_t index) { return oscilloscope[index]; }
    float get_adc_voltage_(uint32_t gpio) { return get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); }
    int32_t test_function(int32_t delta) { static int cnt = 0; return cnt += delta; }
} static_functions;

// When adding new functions/variables to the protocol, be careful not to
// blow the communication stack. You can check comm_stack_info to see
// how much headroom you have.
static inline auto make_obj_tree() {
    return make_protocol_member_list(
        make_protocol_ro_property("vbus_voltage", &vbus_voltage),
        make_protocol_ro_property("serial_number", &serial_number),
        make_protocol_ro_property("hw_version_major", &hw_version_major),
        make_protocol_ro_property("hw_version_minor", &hw_version_minor),
        make_protocol_ro_property("hw_version_variant", &hw_version_variant),
        make_protocol_ro_property("fw_version_major", &fw_version_major),
        make_protocol_ro_property("fw_version_minor", &fw_version_minor),
        make_protocol_ro_property("fw_version_revision", &fw_version_revision),
        make_protocol_ro_property("fw_version_unreleased", &fw_version_unreleased),
        make_protocol_ro_property("user_config_loaded", const_cast<const bool *>(&user_config_loaded_)),
        make_protocol_ro_property("brake_resistor_armed", &brake_resistor_armed),
        make_protocol_object("system_stats",
            make_protocol_ro_property("uptime", &system_stats_.uptime),
            make_protocol_ro_property("min_heap_space", &system_stats_.min_heap_space),
            make_protocol_ro_property("min_stack_space_axis0", &system_stats_.min_stack_space_axis0),
            make_protocol_ro_property("min_stack_space_axis1", &system_stats_.min_stack_space_axis1),
            make_protocol_ro_property("min_stack_space_comms", &system_stats_.min_stack_space_comms),
            make_protocol_ro_property("min_stack_space_usb", &system_stats_.min_stack_space_usb),
            make_protocol_ro_property("min_stack_space_uart", &system_stats_.min_stack_space_uart),
            make_protocol_ro_property("min_stack_space_usb_irq", &system_stats_.min_stack_space_usb_irq),
            make_protocol_ro_property("min_stack_space_startup", &system_stats_.min_stack_space_startup),
            make_protocol_object("usb",
                make_protocol_ro_property("rx_cnt", &usb_stats_.rx_cnt),
                make_protocol_ro_property("tx_cnt", &usb_stats_.tx_cnt),
                make_protocol_ro_property("tx_overrun_cnt", &usb_stats_.tx_overrun_cnt)
            ),
            make_protocol_object("i2c",
                make_protocol_ro_property("addr", &i2c_stats_.addr),
                make_protocol_ro_property("addr_match_cnt", &i2c_stats_.addr_match_cnt),
                make_protocol_ro_property("rx_cnt", &i2c_stats_.rx_cnt),
                make_protocol_ro_property("error_cnt", &i2c_stats_.error_cnt)
            )
        ),
        make_protocol_object("config",
            make_protocol_property("brake_resistance", &board_config.brake_resistance),
            make_protocol_property("max_regen_current ", &board_config.max_regen_current ),
            // TODO: changing this currently requires a reboot - fix this
            make_protocol_property("enable_uart", &board_config.enable_uart),
            make_protocol_property("enable_i2c_instead_of_can" , &board_config.enable_i2c_instead_of_can), // requires a reboot
            make_protocol_property("enable_ascii_protocol_on_usb", &board_config.enable_ascii_protocol_on_usb),
            make_protocol_property("dc_bus_undervoltage_trip_level", &board_config.dc_bus_undervoltage_trip_level),
            make_protocol_property("dc_bus_overvoltage_trip_level", &board_config.dc_bus_overvoltage_trip_level),
#if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3
            make_protocol_object("gpio1_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[0])),
            make_protocol_object("gpio2_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[1])),
            make_protocol_object("gpio3_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[2])),
#endif
            make_protocol_object("gpio4_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[3])),

            make_protocol_object("gpio3_analog_mapping", make_protocol_definitions(board_config.analog_mappings[2])),
            make_protocol_object("gpio4_analog_mapping", make_protocol_definitions(board_config.analog_mappings[3]))
            ),
        make_protocol_object("axis0", axes[0]->make_protocol_definitions()),
        make_protocol_object("axis1", axes[1]->make_protocol_definitions()),
        make_protocol_object("can", can1_ctx.make_protocol_definitions()),
        make_protocol_property("test_property", &test_property),
        make_protocol_function("test_function", static_functions, &StaticFunctions::test_function, "delta"),
        make_protocol_function("get_oscilloscope_val", static_functions, &StaticFunctions::get_oscilloscope_val, "index"),
        make_protocol_function("get_adc_voltage", static_functions, &StaticFunctions::get_adc_voltage_, "gpio"),
        make_protocol_function("save_configuration", static_functions, &StaticFunctions::save_configuration_helper),
        make_protocol_function("erase_configuration", static_functions, &StaticFunctions::erase_configuration_helper),
        make_protocol_function("reboot", static_functions, &StaticFunctions::NVIC_SystemReset_helper),
        make_protocol_function("enter_dfu_mode", static_functions, &StaticFunctions::enter_dfu_mode_helper)
    );
}

using tree_type = decltype(make_obj_tree());
uint8_t tree_buffer[sizeof(tree_type)];

// Thread to handle deffered processing of USB interrupt, and
// read commands out of the UART DMA circular buffer
void communication_task(void * ctx) {
    (void) ctx; // unused parameter

    // TODO: this is supposed to use the move constructor, but currently
    // the compiler uses the copy-constructor instead. Thus the make_obj_tree
    // ends up with a stupid stack size of around 8000 bytes. Fix this.
    auto tree_ptr = new (tree_buffer) tree_type(make_obj_tree());
    fibre_publish(*tree_ptr);

    // Allow main init to continue
    endpoint_list_valid = true;

    start_uart_server();
    start_usb_server();
    if (board_config.enable_i2c_instead_of_can) {
        start_i2c_server();
    } else {
        // TODO: finish implementing CAN
        // start_can_server(can1_ctx, CAN1, serial_number);
    }

    for (;;) {
        osDelay(1000); // nothing to do
    }
}

extern "C" {
int _write(int file, const char* data, int len);
}

// @brief This is what printf calls internally
int _write(int file, const char* data, int len) {
#ifdef USB_PROTOCOL_STDOUT
    usb_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);
#endif
#ifdef UART_PROTOCOL_STDOUT
    uart4_stream_output_ptr->process_bytes((const uint8_t *)data, len, nullptr);
#endif
    return len;
}
<|endoftext|>


<commit_before>// Copyright 2014 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/signin/chrome_signin_client.h"

#include "base/command_line.h"
#include "base/guid.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/cookie_settings.h"
#include "chrome/browser/net/chrome_cookie_notification_details.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/local_auth.h"
#include "chrome/browser/webdata/web_data_service_factory.h"
#include "chrome/common/chrome_version_info.h"
#include "components/metrics/metrics_service.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "components/signin/core/common/signin_pref_names.h"
#include "components/signin/core/common/signin_switches.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/child_process_host.h"
#include "url/gurl.h"

#if defined(ENABLE_MANAGED_USERS)
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#endif

#if defined(OS_CHROMEOS)
#include "components/user_manager/user_manager.h"
#endif

#if !defined(OS_ANDROID)
#include "chrome/browser/first_run/first_run.h"
#endif

using content::ChildProcessHost;
using content::RenderProcessHost;

namespace {

const char kGoogleAccountsUrl[] = "https://accounts.google.com";

}  // namespace

ChromeSigninClient::ChromeSigninClient(Profile* profile)
    : profile_(profile), signin_host_id_(ChildProcessHost::kInvalidUniqueID) {
  callbacks_.set_removal_callback(
    base::Bind(&ChromeSigninClient::UnregisterForCookieChangedNotification,
               base::Unretained(this)));
}

ChromeSigninClient::~ChromeSigninClient() {
  UnregisterForCookieChangedNotification();

  std::set<RenderProcessHost*>::iterator i;
  for (i = signin_hosts_observed_.begin(); i != signin_hosts_observed_.end();
       ++i) {
    (*i)->RemoveObserver(this);
  }
}

// static
bool ChromeSigninClient::ProfileAllowsSigninCookies(Profile* profile) {
  CookieSettings* cookie_settings =
      CookieSettings::Factory::GetForProfile(profile).get();
  return SettingsAllowSigninCookies(cookie_settings);
}

// static
bool ChromeSigninClient::SettingsAllowSigninCookies(
    CookieSettings* cookie_settings) {
  return cookie_settings &&
         cookie_settings->IsSettingCookieAllowed(GURL(kGoogleAccountsUrl),
                                                 GURL(kGoogleAccountsUrl));
}

void ChromeSigninClient::SetSigninProcess(int process_id) {
  if (process_id == signin_host_id_)
    return;
  DLOG_IF(WARNING, signin_host_id_ != ChildProcessHost::kInvalidUniqueID)
      << "Replacing in-use signin process.";
  signin_host_id_ = process_id;
  RenderProcessHost* host = RenderProcessHost::FromID(process_id);
  DCHECK(host);
  host->AddObserver(this);
  signin_hosts_observed_.insert(host);
}

void ChromeSigninClient::ClearSigninProcess() {
  signin_host_id_ = ChildProcessHost::kInvalidUniqueID;
}

bool ChromeSigninClient::IsSigninProcess(int process_id) const {
  return process_id != ChildProcessHost::kInvalidUniqueID &&
         process_id == signin_host_id_;
}

bool ChromeSigninClient::HasSigninProcess() const {
  return signin_host_id_ != ChildProcessHost::kInvalidUniqueID;
}

void ChromeSigninClient::RenderProcessHostDestroyed(RenderProcessHost* host) {
  // It's possible we're listening to a "stale" renderer because it was replaced
  // with a new process by process-per-site. In either case, stop observing it,
  // but only reset signin_host_id_ tracking if this was from the current signin
  // process.
  signin_hosts_observed_.erase(host);
  if (signin_host_id_ == host->GetID())
    signin_host_id_ = ChildProcessHost::kInvalidUniqueID;
}

PrefService* ChromeSigninClient::GetPrefs() { return profile_->GetPrefs(); }

scoped_refptr<TokenWebData> ChromeSigninClient::GetDatabase() {
  return WebDataServiceFactory::GetTokenWebDataForProfile(
      profile_, Profile::EXPLICIT_ACCESS);
}

bool ChromeSigninClient::CanRevokeCredentials() {
#if defined(OS_CHROMEOS)
  // UserManager may not exist in unit_tests.
  if (user_manager::UserManager::IsInitialized() &&
      user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser()) {
    // Don't allow revoking credentials for Chrome OS supervised users.
    // See http://crbug.com/332032
    LOG(ERROR) << "Attempt to revoke supervised user refresh "
               << "token detected, ignoring.";
    return false;
  }
#else
  // Don't allow revoking credentials for supervised users.
  // See http://crbug.com/332032
  if (profile_->IsSupervised()) {
    LOG(ERROR) << "Attempt to revoke supervised user refresh "
               << "token detected, ignoring.";
    return false;
  }
#endif
  return true;
}

std::string ChromeSigninClient::GetSigninScopedDeviceId() {
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableSigninScopedDeviceId)) {
    return std::string();
  }

  std::string signin_scoped_device_id =
      GetPrefs()->GetString(prefs::kGoogleServicesSigninScopedDeviceId);
  if (signin_scoped_device_id.empty()) {
    // If device_id doesn't exist then generate new and save in prefs.
    signin_scoped_device_id = base::GenerateGUID();
    DCHECK(!signin_scoped_device_id.empty());
    GetPrefs()->SetString(prefs::kGoogleServicesSigninScopedDeviceId,
                          signin_scoped_device_id);
  }
  return signin_scoped_device_id;
}

void ChromeSigninClient::OnSignedOut() {
  GetPrefs()->ClearPref(prefs::kGoogleServicesSigninScopedDeviceId);
  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(profile_->GetPath());
  cache.SetLocalAuthCredentialsOfProfileAtIndex(index, std::string());
}

net::URLRequestContextGetter* ChromeSigninClient::GetURLRequestContext() {
  return profile_->GetRequestContext();
}

bool ChromeSigninClient::ShouldMergeSigninCredentialsIntoCookieJar() {
  // If inline sign in is enabled, but account consistency is not, the user's
  // credentials should be merge into the cookie jar.
  return !switches::IsEnableWebBasedSignin() &&
         !switches::IsEnableAccountConsistency();
}

std::string ChromeSigninClient::GetProductVersion() {
  chrome::VersionInfo chrome_version;
  return chrome_version.CreateVersionString();
}

bool ChromeSigninClient::IsFirstRun() const {
#if defined(OS_ANDROID)
  return false;
#else
  return first_run::IsChromeFirstRun();
#endif
}

base::Time ChromeSigninClient::GetInstallDate() {
  return base::Time::FromTimeT(
      g_browser_process->metrics_service()->GetInstallDate());
}

scoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>
ChromeSigninClient::AddCookieChangedCallback(
    const CookieChangedCallback& callback) {
  scoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>
    subscription = callbacks_.Add(callback);
  RegisterForCookieChangedNotification();
  return subscription.Pass();
}

void ChromeSigninClient::GoogleSigninSucceeded(const std::string& account_id,
                                               const std::string& username,
                                               const std::string& password) {
#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
  // Don't store password hash except for users of new profile management.
  if (switches::IsNewProfileManagement())
    chrome::SetLocalAuthCredentials(profile_, password);
#endif
}

void ChromeSigninClient::Observe(int type,
                                 const content::NotificationSource& source,
                                 const content::NotificationDetails& details) {
  switch (type) {
    case chrome::NOTIFICATION_COOKIE_CHANGED: {
      DCHECK(!callbacks_.empty());
      const net::CanonicalCookie* cookie =
          content::Details<ChromeCookieDetails>(details).ptr()->cookie;
      callbacks_.Notify(cookie);
      break;
    }
    default:
      NOTREACHED();
      break;
  }
}

void ChromeSigninClient::RegisterForCookieChangedNotification() {
  if (callbacks_.empty())
    return;
  content::Source<Profile> source(profile_);
  if (!registrar_.IsRegistered(
      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))
  registrar_.Add(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);
}

void ChromeSigninClient::UnregisterForCookieChangedNotification() {
  if (!callbacks_.empty())
    return;
  // Note that it's allowed to call this method multiple times without an
  // intervening call to |RegisterForCookieChangedNotification()|.
  content::Source<Profile> source(profile_);
  if (!registrar_.IsRegistered(
      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))
    return;
  registrar_.Remove(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);
}
<commit_msg>Signing out forces the lock bit to be removed.<commit_after>// Copyright 2014 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/signin/chrome_signin_client.h"

#include "base/command_line.h"
#include "base/guid.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/content_settings/cookie_settings.h"
#include "chrome/browser/net/chrome_cookie_notification_details.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/local_auth.h"
#include "chrome/browser/webdata/web_data_service_factory.h"
#include "chrome/common/chrome_version_info.h"
#include "components/metrics/metrics_service.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "components/signin/core/common/signin_pref_names.h"
#include "components/signin/core/common/signin_switches.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/child_process_host.h"
#include "url/gurl.h"

#if defined(ENABLE_MANAGED_USERS)
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#endif

#if defined(OS_CHROMEOS)
#include "components/user_manager/user_manager.h"
#endif

#if !defined(OS_ANDROID)
#include "chrome/browser/first_run/first_run.h"
#endif

using content::ChildProcessHost;
using content::RenderProcessHost;

namespace {

const char kGoogleAccountsUrl[] = "https://accounts.google.com";

}  // namespace

ChromeSigninClient::ChromeSigninClient(Profile* profile)
    : profile_(profile), signin_host_id_(ChildProcessHost::kInvalidUniqueID) {
  callbacks_.set_removal_callback(
    base::Bind(&ChromeSigninClient::UnregisterForCookieChangedNotification,
               base::Unretained(this)));
}

ChromeSigninClient::~ChromeSigninClient() {
  UnregisterForCookieChangedNotification();

  std::set<RenderProcessHost*>::iterator i;
  for (i = signin_hosts_observed_.begin(); i != signin_hosts_observed_.end();
       ++i) {
    (*i)->RemoveObserver(this);
  }
}

// static
bool ChromeSigninClient::ProfileAllowsSigninCookies(Profile* profile) {
  CookieSettings* cookie_settings =
      CookieSettings::Factory::GetForProfile(profile).get();
  return SettingsAllowSigninCookies(cookie_settings);
}

// static
bool ChromeSigninClient::SettingsAllowSigninCookies(
    CookieSettings* cookie_settings) {
  return cookie_settings &&
         cookie_settings->IsSettingCookieAllowed(GURL(kGoogleAccountsUrl),
                                                 GURL(kGoogleAccountsUrl));
}

void ChromeSigninClient::SetSigninProcess(int process_id) {
  if (process_id == signin_host_id_)
    return;
  DLOG_IF(WARNING, signin_host_id_ != ChildProcessHost::kInvalidUniqueID)
      << "Replacing in-use signin process.";
  signin_host_id_ = process_id;
  RenderProcessHost* host = RenderProcessHost::FromID(process_id);
  DCHECK(host);
  host->AddObserver(this);
  signin_hosts_observed_.insert(host);
}

void ChromeSigninClient::ClearSigninProcess() {
  signin_host_id_ = ChildProcessHost::kInvalidUniqueID;
}

bool ChromeSigninClient::IsSigninProcess(int process_id) const {
  return process_id != ChildProcessHost::kInvalidUniqueID &&
         process_id == signin_host_id_;
}

bool ChromeSigninClient::HasSigninProcess() const {
  return signin_host_id_ != ChildProcessHost::kInvalidUniqueID;
}

void ChromeSigninClient::RenderProcessHostDestroyed(RenderProcessHost* host) {
  // It's possible we're listening to a "stale" renderer because it was replaced
  // with a new process by process-per-site. In either case, stop observing it,
  // but only reset signin_host_id_ tracking if this was from the current signin
  // process.
  signin_hosts_observed_.erase(host);
  if (signin_host_id_ == host->GetID())
    signin_host_id_ = ChildProcessHost::kInvalidUniqueID;
}

PrefService* ChromeSigninClient::GetPrefs() { return profile_->GetPrefs(); }

scoped_refptr<TokenWebData> ChromeSigninClient::GetDatabase() {
  return WebDataServiceFactory::GetTokenWebDataForProfile(
      profile_, Profile::EXPLICIT_ACCESS);
}

bool ChromeSigninClient::CanRevokeCredentials() {
#if defined(OS_CHROMEOS)
  // UserManager may not exist in unit_tests.
  if (user_manager::UserManager::IsInitialized() &&
      user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser()) {
    // Don't allow revoking credentials for Chrome OS supervised users.
    // See http://crbug.com/332032
    LOG(ERROR) << "Attempt to revoke supervised user refresh "
               << "token detected, ignoring.";
    return false;
  }
#else
  // Don't allow revoking credentials for supervised users.
  // See http://crbug.com/332032
  if (profile_->IsSupervised()) {
    LOG(ERROR) << "Attempt to revoke supervised user refresh "
               << "token detected, ignoring.";
    return false;
  }
#endif
  return true;
}

std::string ChromeSigninClient::GetSigninScopedDeviceId() {
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableSigninScopedDeviceId)) {
    return std::string();
  }

  std::string signin_scoped_device_id =
      GetPrefs()->GetString(prefs::kGoogleServicesSigninScopedDeviceId);
  if (signin_scoped_device_id.empty()) {
    // If device_id doesn't exist then generate new and save in prefs.
    signin_scoped_device_id = base::GenerateGUID();
    DCHECK(!signin_scoped_device_id.empty());
    GetPrefs()->SetString(prefs::kGoogleServicesSigninScopedDeviceId,
                          signin_scoped_device_id);
  }
  return signin_scoped_device_id;
}

void ChromeSigninClient::OnSignedOut() {
  GetPrefs()->ClearPref(prefs::kGoogleServicesSigninScopedDeviceId);
  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(profile_->GetPath());
  cache.SetLocalAuthCredentialsOfProfileAtIndex(index, std::string());
  cache.SetProfileSigninRequiredAtIndex(index, false);
}

net::URLRequestContextGetter* ChromeSigninClient::GetURLRequestContext() {
  return profile_->GetRequestContext();
}

bool ChromeSigninClient::ShouldMergeSigninCredentialsIntoCookieJar() {
  // If inline sign in is enabled, but account consistency is not, the user's
  // credentials should be merge into the cookie jar.
  return !switches::IsEnableWebBasedSignin() &&
         !switches::IsEnableAccountConsistency();
}

std::string ChromeSigninClient::GetProductVersion() {
  chrome::VersionInfo chrome_version;
  return chrome_version.CreateVersionString();
}

bool ChromeSigninClient::IsFirstRun() const {
#if defined(OS_ANDROID)
  return false;
#else
  return first_run::IsChromeFirstRun();
#endif
}

base::Time ChromeSigninClient::GetInstallDate() {
  return base::Time::FromTimeT(
      g_browser_process->metrics_service()->GetInstallDate());
}

scoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>
ChromeSigninClient::AddCookieChangedCallback(
    const CookieChangedCallback& callback) {
  scoped_ptr<SigninClient::CookieChangedCallbackList::Subscription>
    subscription = callbacks_.Add(callback);
  RegisterForCookieChangedNotification();
  return subscription.Pass();
}

void ChromeSigninClient::GoogleSigninSucceeded(const std::string& account_id,
                                               const std::string& username,
                                               const std::string& password) {
#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
  // Don't store password hash except for users of new profile management.
  if (switches::IsNewProfileManagement())
    chrome::SetLocalAuthCredentials(profile_, password);
#endif
}

void ChromeSigninClient::Observe(int type,
                                 const content::NotificationSource& source,
                                 const content::NotificationDetails& details) {
  switch (type) {
    case chrome::NOTIFICATION_COOKIE_CHANGED: {
      DCHECK(!callbacks_.empty());
      const net::CanonicalCookie* cookie =
          content::Details<ChromeCookieDetails>(details).ptr()->cookie;
      callbacks_.Notify(cookie);
      break;
    }
    default:
      NOTREACHED();
      break;
  }
}

void ChromeSigninClient::RegisterForCookieChangedNotification() {
  if (callbacks_.empty())
    return;
  content::Source<Profile> source(profile_);
  if (!registrar_.IsRegistered(
      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))
  registrar_.Add(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);
}

void ChromeSigninClient::UnregisterForCookieChangedNotification() {
  if (!callbacks_.empty())
    return;
  // Note that it's allowed to call this method multiple times without an
  // intervening call to |RegisterForCookieChangedNotification()|.
  content::Source<Profile> source(profile_);
  if (!registrar_.IsRegistered(
      this, chrome::NOTIFICATION_COOKIE_CHANGED, source))
    return;
  registrar_.Remove(this, chrome::NOTIFICATION_COOKIE_CHANGED, source);
}
<|endoftext|>


<commit_before>// Copyright 2016 Alex Silva Torres
//
// 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 "simple-object.h"

#include <string>
#include <boost/variant.hpp>

#include "obj-type.h"
#include "object-factory.h"

namespace shpp {
namespace internal {

ObjectPtr NullObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr NullObject::Equal(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::NIL) {
    return obj_factory.NewBool(true);
  } else {
    return obj_factory.NewBool(false);
  }
}

ObjectPtr NullObject::NotEqual(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::NIL) {
    return obj_factory.NewBool(false);
  } else {
    return obj_factory.NewBool(true);
  }
}

ObjectPtr NullObject::And(ObjectPtr /*obj*/) {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr NullObject::Or(ObjectPtr obj) {
  return obj->ObjBool();
}

ObjectPtr NullObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr BoolObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(value_);
}

ObjectPtr BoolObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(value_?"true":"false");
}

ObjectPtr BoolObject::Equal(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    return obj_factory.NewBool(value_ == value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    return obj_factory.NewBool(value_ == value);
  }
}

ObjectPtr BoolObject::NotEqual(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    return obj_factory.NewBool(value_ != value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    return obj_factory.NewBool(value_ != value);
  }
}

ObjectPtr BoolObject::And(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (value_ == false) {
    return obj_factory.NewBool(false);
  }

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  }
}

ObjectPtr BoolObject::Or(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (value_ == true) {
    return obj_factory.NewBool(true);
  }

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  }
}

ObjectPtr BoolObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(!value_);
}

////////////////////////////////////////////////////////////////////////////////
/// Int Object
////////////////////////////////////////////////////////////////////////////////

ObjectPtr IntObject::OperationObj(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      int r = OperationArit(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewInt(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float r = OperationArit(value_, real_obj.value(), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::OperationObjInt(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      int r = OperationArit(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewInt(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr IntObject::ObjReal() {
  float v = static_cast<float>(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_real(obj_factory.NewReal(v));

  return obj_real;
}

ObjectPtr IntObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(std::to_string(value_));
}

ObjectPtr IntObject::ObjString() {
  std::string v = std::to_string(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_str(obj_factory.NewString(v));

  return obj_str;
}

ObjectPtr IntObject::OperationObjComp(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      bool r = OperationComp(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      bool r = OperationComp(value_, real_obj.value(), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    default: {
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(false);
    }
  }
}

ObjectPtr IntObject::Copy() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(value_);
}

ObjectPtr IntObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr IntObject::Add(ObjectPtr obj) {
  return OperationObj(obj, 0);
}

ObjectPtr IntObject::Sub(ObjectPtr obj) {
  return OperationObj(obj, 1);
}

ObjectPtr IntObject::Mult(ObjectPtr obj) {
  return OperationObj(obj, 2);
}

ObjectPtr IntObject::Div(ObjectPtr obj) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      float b = int_obj.value();

      if (b == 0) {
        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,
                           boost::format("zero div indetermined"));
      }

      float r = static_cast<float>(value_)/ b;
      ObjectFactory obj_factory(symbol_table_stack());
      if ((value_% int_obj.value_) != 0) {
        return obj_factory.NewReal(r);
      } else {
        return obj_factory.NewInt(static_cast<int>(r));
      }
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float b = real_obj.value();

      if (b == static_cast<float>(0)) {
        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,
                           boost::format("zero div indetermined"));
      }

      float r = static_cast<float>(value_)/ b;
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::DivMod(ObjectPtr obj) {
  return OperationObjInt(obj, 4);
}

ObjectPtr IntObject::RightShift(ObjectPtr obj) {
  return OperationObjInt(obj, 5);
}

ObjectPtr IntObject::LeftShift(ObjectPtr obj) {
  return OperationObjInt(obj, 6);
}

ObjectPtr IntObject::Lesser(ObjectPtr obj) {
  return OperationObjComp(obj, 0);
}

ObjectPtr IntObject::Greater(ObjectPtr obj) {
  return OperationObjComp(obj, 1);
}

ObjectPtr IntObject::LessEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 2);
}

ObjectPtr IntObject::GreatEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 3);
}

ObjectPtr IntObject::Equal(ObjectPtr obj) {
  return OperationObjComp(obj, 4);
}

ObjectPtr IntObject::NotEqual(ObjectPtr obj) {
  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {
    ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(true);
  }

  return OperationObjComp(obj, 5);
}

ObjectPtr IntObject::BitAnd(ObjectPtr obj) {
  return OperationObjInt(obj, 7);
}

ObjectPtr IntObject::BitOr(ObjectPtr obj) {
  return OperationObjInt(obj, 8);
}

ObjectPtr IntObject::BitXor(ObjectPtr obj) {
  return OperationObjInt(obj, 9);
}

ObjectPtr IntObject::BitNot() {
  int r = ~value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

ObjectPtr IntObject::UnaryAdd() {
  int r = +value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

ObjectPtr IntObject::UnarySub() {
  int r = -value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

////////////////////////////////////////////////////////////////////////////////
/// Real Object
////////////////////////////////////////////////////////////////////////////////
ObjectPtr RealObject::OperationObj(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      float r = OperationArit(value_, static_cast<float>(int_obj.value()), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float r = OperationArit(value_, real_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr RealObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr RealObject::ObjInt() {
  int v = static_cast<int>(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_int(obj_factory.NewReal(v));
  return obj_int;
}

ObjectPtr RealObject::ObjString() {
  std::string v = std::to_string(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_str(obj_factory.NewString(v));

  return obj_str;
}

ObjectPtr RealObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(std::to_string(value_));
}

ObjectPtr RealObject::OperationObjComp(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      bool r = OperationComp(value_, static_cast<float>(int_obj.value()), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      bool r = OperationComp(value_, real_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr RealObject::Copy() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(value_);
}

ObjectPtr RealObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr RealObject::Add(ObjectPtr obj) {
  return OperationObj(obj, 0);
}

ObjectPtr RealObject::Sub(ObjectPtr obj) {
  return OperationObj(obj, 1);
}

ObjectPtr RealObject::Mult(ObjectPtr obj) {
  return OperationObj(obj, 2);
}

ObjectPtr RealObject::Div(ObjectPtr obj) {
  return OperationObj(obj, 3);
}

ObjectPtr RealObject::Lesser(ObjectPtr obj) {
  return OperationObjComp(obj, 0);
}

ObjectPtr RealObject::Greater(ObjectPtr obj) {
  return OperationObjComp(obj, 1);
}

ObjectPtr RealObject::LessEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 2);
}

ObjectPtr RealObject::GreatEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 3);
}

ObjectPtr RealObject::Equal(ObjectPtr obj) {
  return OperationObjComp(obj, 4);
}

ObjectPtr RealObject::NotEqual(ObjectPtr obj) {
  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {
    ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(true);
  }

  return OperationObjComp(obj, 5);
}

ObjectPtr RealObject::UnaryAdd() {
  float r = +value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(r);
}

ObjectPtr RealObject::UnarySub() {
  float r = -value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(r);
}

}
}
<commit_msg>fix float to int converstion<commit_after>// Copyright 2016 Alex Silva Torres
//
// 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 "simple-object.h"

#include <string>
#include <boost/variant.hpp>

#include "obj-type.h"
#include "object-factory.h"

namespace shpp {
namespace internal {

ObjectPtr NullObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr NullObject::Equal(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::NIL) {
    return obj_factory.NewBool(true);
  } else {
    return obj_factory.NewBool(false);
  }
}

ObjectPtr NullObject::NotEqual(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::NIL) {
    return obj_factory.NewBool(false);
  } else {
    return obj_factory.NewBool(true);
  }
}

ObjectPtr NullObject::And(ObjectPtr /*obj*/) {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr NullObject::Or(ObjectPtr obj) {
  return obj->ObjBool();
}

ObjectPtr NullObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr BoolObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(value_);
}

ObjectPtr BoolObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(value_?"true":"false");
}

ObjectPtr BoolObject::Equal(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    return obj_factory.NewBool(value_ == value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    return obj_factory.NewBool(value_ == value);
  }
}

ObjectPtr BoolObject::NotEqual(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    return obj_factory.NewBool(value_ != value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    return obj_factory.NewBool(value_ != value);
  }
}

ObjectPtr BoolObject::And(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (value_ == false) {
    return obj_factory.NewBool(false);
  }

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  }
}

ObjectPtr BoolObject::Or(ObjectPtr obj) {
  ObjectFactory obj_factory(symbol_table_stack());

  if (value_ == true) {
    return obj_factory.NewBool(true);
  }

  if (obj->type() == ObjectType::BOOL) {
    bool value = static_cast<const BoolObject&>(*obj).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  } else {
    ObjectPtr obj_bool = obj->ObjBool();
    bool value = static_cast<const BoolObject&>(*obj_bool).value_;
    ObjectFactory obj_factory(symbol_table_stack());
    return obj_factory.NewBool(value);
  }
}

ObjectPtr BoolObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(!value_);
}

////////////////////////////////////////////////////////////////////////////////
/// Int Object
////////////////////////////////////////////////////////////////////////////////

ObjectPtr IntObject::OperationObj(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      int r = OperationArit(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewInt(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float r = OperationArit(value_, real_obj.value(), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::OperationObjInt(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      int r = OperationArit(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewInt(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr IntObject::ObjReal() {
  float v = static_cast<float>(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_real(obj_factory.NewReal(v));

  return obj_real;
}

ObjectPtr IntObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(std::to_string(value_));
}

ObjectPtr IntObject::ObjString() {
  std::string v = std::to_string(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_str(obj_factory.NewString(v));

  return obj_str;
}

ObjectPtr IntObject::OperationObjComp(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      bool r = OperationComp(value_, int_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      bool r = OperationComp(value_, real_obj.value(), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    default: {
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(false);
    }
  }
}

ObjectPtr IntObject::Copy() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(value_);
}

ObjectPtr IntObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr IntObject::Add(ObjectPtr obj) {
  return OperationObj(obj, 0);
}

ObjectPtr IntObject::Sub(ObjectPtr obj) {
  return OperationObj(obj, 1);
}

ObjectPtr IntObject::Mult(ObjectPtr obj) {
  return OperationObj(obj, 2);
}

ObjectPtr IntObject::Div(ObjectPtr obj) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      float b = int_obj.value();

      if (b == 0) {
        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,
                           boost::format("zero div indetermined"));
      }

      float r = static_cast<float>(value_)/ b;
      ObjectFactory obj_factory(symbol_table_stack());
      if ((value_% int_obj.value_) != 0) {
        return obj_factory.NewReal(r);
      } else {
        return obj_factory.NewInt(static_cast<int>(r));
      }
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float b = real_obj.value();

      if (b == static_cast<float>(0)) {
        throw RunTimeError(RunTimeError::ErrorCode::ZERO_DIV,
                           boost::format("zero div indetermined"));
      }

      float r = static_cast<float>(value_)/ b;
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr IntObject::DivMod(ObjectPtr obj) {
  return OperationObjInt(obj, 4);
}

ObjectPtr IntObject::RightShift(ObjectPtr obj) {
  return OperationObjInt(obj, 5);
}

ObjectPtr IntObject::LeftShift(ObjectPtr obj) {
  return OperationObjInt(obj, 6);
}

ObjectPtr IntObject::Lesser(ObjectPtr obj) {
  return OperationObjComp(obj, 0);
}

ObjectPtr IntObject::Greater(ObjectPtr obj) {
  return OperationObjComp(obj, 1);
}

ObjectPtr IntObject::LessEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 2);
}

ObjectPtr IntObject::GreatEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 3);
}

ObjectPtr IntObject::Equal(ObjectPtr obj) {
  return OperationObjComp(obj, 4);
}

ObjectPtr IntObject::NotEqual(ObjectPtr obj) {
  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {
    ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(true);
  }

  return OperationObjComp(obj, 5);
}

ObjectPtr IntObject::BitAnd(ObjectPtr obj) {
  return OperationObjInt(obj, 7);
}

ObjectPtr IntObject::BitOr(ObjectPtr obj) {
  return OperationObjInt(obj, 8);
}

ObjectPtr IntObject::BitXor(ObjectPtr obj) {
  return OperationObjInt(obj, 9);
}

ObjectPtr IntObject::BitNot() {
  int r = ~value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

ObjectPtr IntObject::UnaryAdd() {
  int r = +value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

ObjectPtr IntObject::UnarySub() {
  int r = -value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewInt(r);
}

////////////////////////////////////////////////////////////////////////////////
/// Real Object
////////////////////////////////////////////////////////////////////////////////
ObjectPtr RealObject::OperationObj(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      float r = OperationArit(value_, static_cast<float>(int_obj.value()), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      float r = OperationArit(value_, real_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr RealObject::Not() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(false);
}

ObjectPtr RealObject::ObjInt() {
  int v = static_cast<int>(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_int(obj_factory.NewInt(v));
  return obj_int;
}

ObjectPtr RealObject::ObjString() {
  std::string v = std::to_string(value_);

  ObjectFactory obj_factory(symbol_table_stack());
  ObjectPtr obj_str(obj_factory.NewString(v));

  return obj_str;
}

ObjectPtr RealObject::ObjCmd() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewString(std::to_string(value_));
}

ObjectPtr RealObject::OperationObjComp(ObjectPtr obj, int op) {
  switch (obj->type()) {
    case ObjectType::INT: {
      IntObject& int_obj = static_cast<IntObject&>(*obj);
      bool r = OperationComp(value_, static_cast<float>(int_obj.value()), op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    case ObjectType::REAL: {
      RealObject& real_obj = static_cast<RealObject&>(*obj);
      bool r = OperationComp(value_, real_obj.value_, op);
      ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewBool(r);
    } break;

    default:
      throw RunTimeError(RunTimeError::ErrorCode::INCOMPATIBLE_TYPE,
                         boost::format("type not supported"));
  }
}

ObjectPtr RealObject::Copy() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(value_);
}

ObjectPtr RealObject::ObjBool() {
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewBool(true);
}

ObjectPtr RealObject::Add(ObjectPtr obj) {
  return OperationObj(obj, 0);
}

ObjectPtr RealObject::Sub(ObjectPtr obj) {
  return OperationObj(obj, 1);
}

ObjectPtr RealObject::Mult(ObjectPtr obj) {
  return OperationObj(obj, 2);
}

ObjectPtr RealObject::Div(ObjectPtr obj) {
  return OperationObj(obj, 3);
}

ObjectPtr RealObject::Lesser(ObjectPtr obj) {
  return OperationObjComp(obj, 0);
}

ObjectPtr RealObject::Greater(ObjectPtr obj) {
  return OperationObjComp(obj, 1);
}

ObjectPtr RealObject::LessEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 2);
}

ObjectPtr RealObject::GreatEqual(ObjectPtr obj) {
  return OperationObjComp(obj, 3);
}

ObjectPtr RealObject::Equal(ObjectPtr obj) {
  return OperationObjComp(obj, 4);
}

ObjectPtr RealObject::NotEqual(ObjectPtr obj) {
  if (obj->type() != ObjectType::INT && obj->type() != ObjectType::REAL) {
    ObjectFactory obj_factory(symbol_table_stack());
      return obj_factory.NewReal(true);
  }

  return OperationObjComp(obj, 5);
}

ObjectPtr RealObject::UnaryAdd() {
  float r = +value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(r);
}

ObjectPtr RealObject::UnarySub() {
  float r = -value_;
  ObjectFactory obj_factory(symbol_table_stack());
  return obj_factory.NewReal(r);
}

}
}
<|endoftext|>


<commit_before>/*
 * AbstractTexQuartzRenderer.cpp
 *
 * Copyright (C) 2018 by VISUS (Universitaet Stuttgart)
 * Alle Rechte vorbehalten.
 */
#include "stdafx.h"
#include "AbstractTexQuartzRenderer.h"
#include "vislib/graphics/gl/IncludeAllGL.h"

namespace megamol {
namespace demos {

/*
 * AbstractTexQuartzRenderer::AbstractTexQuartzRenderer
 */
AbstractTexQuartzRenderer::AbstractTexQuartzRenderer(void)
    : AbstractQuartzRenderer(), typeTexture(0) {
}

/*
 * AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer
 */
AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer(void) {
}

/*
 * AbstractTexQuartzRenderer::assertTypeTexture
 */
void AbstractTexQuartzRenderer::assertTypeTexture(CrystalDataCall& types) {
    if ((this->typesDataHash != 0) && (this->typesDataHash == types.DataHash())) return; // all up to date
    this->typesDataHash = types.DataHash();

    if (types.GetCount() == 0) {
        ::glDeleteTextures(1, &this->typeTexture);
        this->typeTexture = 0;
        return;
    }
    if (this->typeTexture == 0) {
        ::glGenTextures(1, &this->typeTexture);
    }

    unsigned mfc = 0;
    for (unsigned int i = 0; i < types.GetCount(); i++) {
        if (mfc < types.GetCrystals()[i].GetFaceCount()) {
            mfc = types.GetCrystals()[i].GetFaceCount();
        }
    }

    float *dat = new float[types.GetCount() * mfc * 4];

    for (unsigned int y = 0; y < types.GetCount(); y++) {
        const CrystalDataCall::Crystal& c = types.GetCrystals()[y];
        unsigned int x;
        for (x = 0; x < c.GetFaceCount(); x++) {
            vislib::math::Vector<float, 3> f = c.GetFace(x);
            dat[(x + y * mfc) * 4 + 3] = f.Normalise();
            dat[(x + y * mfc) * 4 + 0] = f.X();
            dat[(x + y * mfc) * 4 + 1] = f.Y();
            dat[(x + y * mfc) * 4 + 2] = f.Z();
        }
        for (; x < mfc; x++) {
            dat[(x + y * mfc) * 4 + 0] = 0.0f;
            dat[(x + y * mfc) * 4 + 1] = 0.0f;
            dat[(x + y * mfc) * 4 + 2] = 0.0f;
            dat[(x + y * mfc) * 4 + 3] = 0.0f;
        }
    }

    ::glBindTexture(GL_TEXTURE_2D, this->typeTexture);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    ::glPixelStorei(GL_PACK_ALIGNMENT, 1);
    ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, mfc, types.GetCount(), 0, GL_RGBA, GL_FLOAT, dat);
    ::glBindTexture(GL_TEXTURE_2D, 0);

    delete[] dat;
}

/*
 * AbstractTexQuartzRenderer::releaseTypeTexture
 */
void AbstractTexQuartzRenderer::releaseTypeTexture(void) {
    ::glDeleteTextures(1, &this->typeTexture);
    this->typeTexture = 0;
}

} /* end namespace demos */
} /* end namespace megamol */<commit_msg>pwdemos: dont use new/delete in AbstractTexQuartzRenderer<commit_after>/*
 * AbstractTexQuartzRenderer.cpp
 *
 * Copyright (C) 2018 by VISUS (Universitaet Stuttgart)
 * Alle Rechte vorbehalten.
 */
#include "stdafx.h"
#include "AbstractTexQuartzRenderer.h"
#include "vislib/graphics/gl/IncludeAllGL.h"
#include <vector>

namespace megamol {
namespace demos {

/*
 * AbstractTexQuartzRenderer::AbstractTexQuartzRenderer
 */
AbstractTexQuartzRenderer::AbstractTexQuartzRenderer(void)
    : AbstractQuartzRenderer(), typeTexture(0) {
}

/*
 * AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer
 */
AbstractTexQuartzRenderer::~AbstractTexQuartzRenderer(void) {
}

/*
 * AbstractTexQuartzRenderer::assertTypeTexture
 */
void AbstractTexQuartzRenderer::assertTypeTexture(CrystalDataCall& types) {
    if ((this->typesDataHash != 0) && (this->typesDataHash == types.DataHash())) return; // all up to date
    this->typesDataHash = types.DataHash();

    if (types.GetCount() == 0) {
        ::glDeleteTextures(1, &this->typeTexture);
        this->typeTexture = 0;
        return;
    }
    if (this->typeTexture == 0) {
        ::glGenTextures(1, &this->typeTexture);
    }

    unsigned mfc = 0;
    for (unsigned int i = 0; i < types.GetCount(); i++) {
        if (mfc < types.GetCrystals()[i].GetFaceCount()) {
            mfc = types.GetCrystals()[i].GetFaceCount();
        }
    }

    std::vector<float> dat;
    dat.resize(types.GetCount() * mfc * 4);

    for (unsigned int y = 0; y < types.GetCount(); y++) {
        const CrystalDataCall::Crystal& c = types.GetCrystals()[y];
        unsigned int x;
        for (x = 0; x < c.GetFaceCount(); x++) {
            vislib::math::Vector<float, 3> f = c.GetFace(x);
            dat[(x + y * mfc) * 4 + 3] = f.Normalise();
            dat[(x + y * mfc) * 4 + 0] = f.X();
            dat[(x + y * mfc) * 4 + 1] = f.Y();
            dat[(x + y * mfc) * 4 + 2] = f.Z();
        }
        for (; x < mfc; x++) {
            dat[(x + y * mfc) * 4 + 0] = 0.0f;
            dat[(x + y * mfc) * 4 + 1] = 0.0f;
            dat[(x + y * mfc) * 4 + 2] = 0.0f;
            dat[(x + y * mfc) * 4 + 3] = 0.0f;
        }
    }

    ::glBindTexture(GL_TEXTURE_2D, this->typeTexture);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    GLint initial_pack_alignment = 0;
    ::glGetIntegerv(GL_PACK_ALIGNMENT, &initial_pack_alignment);
    ::glPixelStorei(GL_PACK_ALIGNMENT, 1);

    ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, mfc, types.GetCount(), 0, GL_RGBA, GL_FLOAT, dat.data());
    ::glBindTexture(GL_TEXTURE_2D, 0);

    ::glPixelStorei(GL_PACK_ALIGNMENT, initial_pack_alignment);

}

/*
 * AbstractTexQuartzRenderer::releaseTypeTexture
 */
void AbstractTexQuartzRenderer::releaseTypeTexture(void) {
    ::glDeleteTextures(1, &this->typeTexture);
    this->typeTexture = 0;
}

} /* end namespace demos */
} /* end namespace megamol */<|endoftext|>


<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 "chrome/browser/signin/signin_header_helper.h"

#include "chrome/browser/extensions/extension_renderer_state.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/profile_management_switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"

#if defined(OS_ANDROID)
#include "chrome/browser/android/signin/account_management_screen_helper.h"
#endif  // defined(OS_ANDROID)

namespace {

const char kChromeConnectedHeader[] = "X-Chrome-Connected";
const char kChromeManageAccountsHeader[] = "X-Chrome-Manage-Accounts";
const char kGaiaAuthExtensionID[] = "mfffpogegjflfpflabcdkioaeobkgjik";

// Show profile avatar bubble on UI thread. Must be called on the UI thread.
void ShowAvatarBubbleUIThread(int child_id, int route_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  content::WebContents* web_contents =
      tab_util::GetWebContentsByID(child_id, route_id);
  if (!web_contents)
    return;

#if !defined(OS_ANDROID)
  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
  if (browser)
    browser->window()->ShowAvatarBubbleFromAvatarButton();
  // TODO(guohui): need to handle the case when avatar button is not available.
#else  // defined(OS_ANDROID)
  AccountManagementScreenHelper::OpenAccountManagementScreen(
      Profile::FromBrowserContext(web_contents->GetBrowserContext()));
#endif // OS_ANDROID
}

bool IsDriveOrigin(const GURL& url) {
  if (!url.SchemeIsSecure())
    return false;

  const GURL kGoogleDriveURL("https://drive.google.com");
  const GURL kGoogleDocsURL("https://docs.google.com");
  return url == kGoogleDriveURL || url == kGoogleDocsURL;
}

} // empty namespace

namespace signin {

void AppendMirrorRequestHeaderIfPossible(
    net::URLRequest* request,
    const GURL& redirect_url,
    ProfileIOData* io_data,
    int child_id,
    int route_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

   if (io_data->is_incognito() ||
       io_data->google_services_username()->GetValue().empty()) {
     return;
   }

  // Only set the header for Gaia (in the mirror world) and Drive. Gaia needs
  // the header to redirect certain user actions to Chrome native UI. Drive
  // needs the header to tell if the current user is connected. The drive path
  // is a temporary workaround until the more generic chrome.principals API is
  // available.
  const GURL& url = redirect_url.is_empty() ? request->url() : redirect_url;
  GURL origin(url.GetOrigin());
  bool is_gaia_origin = !switches::IsEnableWebBasedSignin() &&
      switches::IsNewProfileManagement() &&
      gaia::IsGaiaSignonRealm(origin);
  if (!is_gaia_origin && !IsDriveOrigin(origin))
    return;

  ExtensionRendererState* renderer_state =
      ExtensionRendererState::GetInstance();
  ExtensionRendererState::WebViewInfo webview_info;
  bool is_guest = renderer_state->GetWebViewInfo(
      child_id, route_id, &webview_info);
  if (is_guest && webview_info.embedder_extension_id == kGaiaAuthExtensionID){
    return;
  }

  std::string account_id(io_data->google_services_account_id()->GetValue());
  if (account_id.empty())
    account_id = "1"; // Dummy value if focus ID not available yet.

  request->SetExtraRequestHeaderByName(
      kChromeConnectedHeader, account_id, false);
}

void ProcessMirrorResponseHeaderIfExists(
    net::URLRequest* request,
    ProfileIOData* io_data,
    int child_id,
    int route_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  if (gaia::IsGaiaSignonRealm(request->url().GetOrigin()) &&
      request->response_headers()->HasHeader(kChromeManageAccountsHeader)) {
    DCHECK(switches::IsNewProfileManagement() &&
           !io_data->is_incognito());
    content::BrowserThread::PostTask(
        content::BrowserThread::UI, FROM_HERE,
        base::Bind(ShowAvatarBubbleUIThread, child_id, route_id));
  }
}

} // namespace signin
<commit_msg>Enables x-chrome-connected header for all google properties<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 "chrome/browser/signin/signin_header_helper.h"

#include "chrome/browser/extensions/extension_renderer_state.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/profile_management_switches.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"

#if defined(OS_ANDROID)
#include "chrome/browser/android/signin/account_management_screen_helper.h"
#endif  // defined(OS_ANDROID)

namespace {

const char kChromeConnectedHeader[] = "X-Chrome-Connected";
const char kChromeManageAccountsHeader[] = "X-Chrome-Manage-Accounts";
const char kGaiaAuthExtensionID[] = "mfffpogegjflfpflabcdkioaeobkgjik";

// Show profile avatar bubble on UI thread. Must be called on the UI thread.
void ShowAvatarBubbleUIThread(int child_id, int route_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  content::WebContents* web_contents =
      tab_util::GetWebContentsByID(child_id, route_id);
  if (!web_contents)
    return;

#if !defined(OS_ANDROID)
  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
  if (browser)
    browser->window()->ShowAvatarBubbleFromAvatarButton();
  // TODO(guohui): need to handle the case when avatar button is not available.
#else  // defined(OS_ANDROID)
  AccountManagementScreenHelper::OpenAccountManagementScreen(
      Profile::FromBrowserContext(web_contents->GetBrowserContext()));
#endif // OS_ANDROID
}

bool IsDriveOrigin(const GURL& url) {
  if (!url.SchemeIsSecure())
    return false;

  const GURL kGoogleDriveURL("https://drive.google.com");
  const GURL kGoogleDocsURL("https://docs.google.com");
  return url == kGoogleDriveURL || url == kGoogleDocsURL;
}

} // empty namespace

namespace signin {

void AppendMirrorRequestHeaderIfPossible(
    net::URLRequest* request,
    const GURL& redirect_url,
    ProfileIOData* io_data,
    int child_id,
    int route_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

   if (io_data->is_incognito() ||
       io_data->google_services_username()->GetValue().empty()) {
     return;
   }

  // Only set the header for Drive always, and other Google properties if
  // new-profile-management is enabled.
  // Vasquette, which is integrated with most Google properties, needs the
  // header to redirect certain user actions to Chrome native UI. Drive needs
  // the header to tell if the current user is connected. The drive path is a
  // temporary workaround until the more generic chrome.principals API is
  // available.
  const GURL& url = redirect_url.is_empty() ? request->url() : redirect_url;
  GURL origin(url.GetOrigin());
  bool is_google_url =
      !switches::IsEnableWebBasedSignin() &&
      switches::IsNewProfileManagement() &&
      google_util::IsGoogleDomainUrl(
          url,
          google_util::ALLOW_SUBDOMAIN,
          google_util::DISALLOW_NON_STANDARD_PORTS);
  if (!is_google_url && !IsDriveOrigin(origin))
    return;

  ExtensionRendererState* renderer_state =
      ExtensionRendererState::GetInstance();
  ExtensionRendererState::WebViewInfo webview_info;
  bool is_guest = renderer_state->GetWebViewInfo(
      child_id, route_id, &webview_info);
  if (is_guest && webview_info.embedder_extension_id == kGaiaAuthExtensionID){
    return;
  }

  std::string account_id(io_data->google_services_account_id()->GetValue());
  if (account_id.empty())
    account_id = "1"; // Dummy value if focus ID not available yet.

  request->SetExtraRequestHeaderByName(
      kChromeConnectedHeader, account_id, false);
}

void ProcessMirrorResponseHeaderIfExists(
    net::URLRequest* request,
    ProfileIOData* io_data,
    int child_id,
    int route_id) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  if (gaia::IsGaiaSignonRealm(request->url().GetOrigin()) &&
      request->response_headers()->HasHeader(kChromeManageAccountsHeader)) {
    DCHECK(switches::IsNewProfileManagement() &&
           !io_data->is_incognito());
    content::BrowserThread::PostTask(
        content::BrowserThread::UI, FROM_HERE,
        base::Bind(ShowAvatarBubbleUIThread, child_id, route_id));
  }
}

} // namespace signin
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Mikhail Baranov
 * Copyright (c) 2015 Victor Gaydov
 *
 * 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/.
 */

#include <stdio.h>

#include "roc_core/print.h"
#include "roc_packet/address_to_str.h"
#include "roc_packet/packet.h"
#include "roc_packet/print.h"

namespace roc {
namespace packet {

void print(const Packet& p, int flags) {
    if (p.udp()) {
        fprintf(stderr, "udp: src=%s dst=%s\n", address_to_str(p.udp()->src_addr).c_str(),
                address_to_str(p.udp()->dst_addr).c_str());
    }

    if (p.rtp()) {
        fprintf(stderr, "rtp: src=%lu m=%d, sn=%lu, ts=%lu dur=%lu pt=%u payload=%lu\n",
                (unsigned long)p.rtp()->source, (int)p.rtp()->marker,
                (unsigned long)p.rtp()->seqnum, (unsigned long)p.rtp()->timestamp,
                (unsigned long)p.rtp()->duration, (unsigned int)p.rtp()->payload_type,
                (unsigned long)p.rtp()->payload.size());

        if ((flags & PrintPayload) && p.rtp()->payload) {
            core::print_bytes(p.rtp()->payload.data(), p.rtp()->payload.size());
        }
    }

    if (p.fec()) {
        fprintf(stderr, "fec: data_blk/fec_blk=%lu payload=%lu\n",
                (unsigned long)p.fec()->blknum, (unsigned long)p.fec()->payload.size());

        if ((flags & PrintPayload) && p.fec()->payload) {
            core::print_bytes(p.fec()->payload.data(), p.fec()->payload.size());
        }
    }
}

} // namespace packet
} // namespace roc
<commit_msg>roc_packet: Fix print()<commit_after>/*
 * Copyright (c) 2015 Mikhail Baranov
 * Copyright (c) 2015 Victor Gaydov
 *
 * 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/.
 */

#include <stdio.h>

#include "roc_core/print.h"
#include "roc_packet/address_to_str.h"
#include "roc_packet/packet.h"
#include "roc_packet/print.h"

namespace roc {
namespace packet {

void print(const Packet& p, int flags) {
    if (p.udp()) {
        fprintf(stderr, "udp: src=%s dst=%s\n", address_to_str(p.udp()->src_addr).c_str(),
                address_to_str(p.udp()->dst_addr).c_str());
    }

    if (p.rtp()) {
        fprintf(stderr, "rtp: src=%lu m=%d sn=%lu ts=%lu dur=%lu pt=%u payload=%lu\n",
                (unsigned long)p.rtp()->source, (int)p.rtp()->marker,
                (unsigned long)p.rtp()->seqnum, (unsigned long)p.rtp()->timestamp,
                (unsigned long)p.rtp()->duration, (unsigned int)p.rtp()->payload_type,
                (unsigned long)p.rtp()->payload.size());

        if ((flags & PrintPayload) && p.rtp()->payload) {
            core::print_bytes(p.rtp()->payload.data(), p.rtp()->payload.size());
        }
    }

    if (p.fec()) {
        fprintf(stderr, "fec: blk=%lu payload=%lu\n",
                (unsigned long)p.fec()->blknum, (unsigned long)p.fec()->payload.size());

        if ((flags & PrintPayload) && p.fec()->payload) {
            core::print_bytes(p.fec()->payload.data(), p.fec()->payload.size());
        }
    }
}

} // namespace packet
} // namespace roc
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: CDriver.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: oj $ $Date: 2002-08-21 13:15:00 $
 *
 *  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 _CONNECTIVITY_CALC_DRIVER_HXX_
#include "calc/CDriver.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CONNECTION_HXX_
#include "calc/CConnection.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif

using namespace connectivity::calc;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

//------------------------------------------------------------------------------
// static ServiceInfo

rtl::OUString ODriver::getImplementationName_Static(  ) throw(RuntimeException)
{
    return rtl::OUString::createFromAscii("com.sun.star.comp.sdbc.calc.ODriver");
}

::rtl::OUString SAL_CALL ODriver::getImplementationName(  ) throw(RuntimeException)
{
    return getImplementationName_Static();
}

// service names from file::OFileDriver

//------------------------------------------------------------------

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
    connectivity::calc::ODriver_CreateInstance(const ::com::sun::star::uno::Reference<
        ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
{
    return *(new ODriver(_rxFactory));
}

Reference< XConnection > SAL_CALL ODriver::connect( const ::rtl::OUString& url,
    const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if (ODriver_BASE::rBHelper.bDisposed)
        throw DisposedException();

    if ( ! acceptsURL(url) )
        return NULL;

    OCalcConnection* pCon = new OCalcConnection(this);
    pCon->construct(url,info);
    Reference< XConnection > xCon = pCon;
    m_xConnections.push_back(WeakReferenceHelper(*pCon));

    return xCon;
}

sal_Bool SAL_CALL ODriver::acceptsURL( const ::rtl::OUString& url )
                throw(SQLException, RuntimeException)
{
    if(!url.compareTo(::rtl::OUString::createFromAscii("sdbc:calc:"),10))
    {
        return sal_True;
    }
    return sal_False;
}

<commit_msg>INTEGRATION: CWS insight01 (1.4.94); FILE MERGED 2003/08/04 06:11:36 oj 1.4.94.1: #111075# ongoing work<commit_after>/*************************************************************************
 *
 *  $RCSfile: CDriver.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 16:59:02 $
 *
 *  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 _CONNECTIVITY_CALC_DRIVER_HXX_
#include "calc/CDriver.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CONNECTION_HXX_
#include "calc/CConnection.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif

using namespace connectivity::calc;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;

//------------------------------------------------------------------------------
// static ServiceInfo

rtl::OUString ODriver::getImplementationName_Static(  ) throw(RuntimeException)
{
    return rtl::OUString::createFromAscii("com.sun.star.comp.sdbc.calc.ODriver");
}

::rtl::OUString SAL_CALL ODriver::getImplementationName(  ) throw(RuntimeException)
{
    return getImplementationName_Static();
}

// service names from file::OFileDriver

//------------------------------------------------------------------

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
    connectivity::calc::ODriver_CreateInstance(const ::com::sun::star::uno::Reference<
        ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
{
    return *(new ODriver(_rxFactory));
}

Reference< XConnection > SAL_CALL ODriver::connect( const ::rtl::OUString& url,
    const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if (ODriver_BASE::rBHelper.bDisposed)
        throw DisposedException();

    if ( ! acceptsURL(url) )
        return NULL;

    OCalcConnection* pCon = new OCalcConnection(this);
    pCon->construct(url,info);
    Reference< XConnection > xCon = pCon;
    m_xConnections.push_back(WeakReferenceHelper(*pCon));

    return xCon;
}

sal_Bool SAL_CALL ODriver::acceptsURL( const ::rtl::OUString& url )
                throw(SQLException, RuntimeException)
{
    if(!url.compareTo(::rtl::OUString::createFromAscii("sdbc:calc:"),10))
    {
        return sal_True;
    }
    return sal_False;
}

Sequence< DriverPropertyInfo > SAL_CALL ODriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
    if ( !acceptsURL(url) )
        ::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Invalid URL!")) ,*this);
    return Sequence< DriverPropertyInfo >();
}
// -----------------------------------------------------------------------------

<|endoftext|>