<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 "extensions/browser/api/device_permissions_prompt.h"

#include "base/bind.h"
#include "base/scoped_observer.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "device/core/device_client.h"
#include "device/hid/hid_device_filter.h"
#include "device/hid/hid_device_info.h"
#include "device/hid/hid_service.h"
#include "device/usb/usb_device.h"
#include "device/usb/usb_device_filter.h"
#include "device/usb/usb_ids.h"
#include "device/usb/usb_service.h"
#include "extensions/browser/api/device_permissions_manager.h"
#include "extensions/common/extension.h"
#include "extensions/strings/grit/extensions_strings.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(OS_CHROMEOS)
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/permission_broker_client.h"
#endif  // defined(OS_CHROMEOS)

using device::HidDeviceFilter;
using device::HidService;
using device::UsbDevice;
using device::UsbDeviceFilter;
using device::UsbService;

namespace extensions {

namespace {

class UsbDeviceInfo : public DevicePermissionsPrompt::Prompt::DeviceInfo {
 public:
  UsbDeviceInfo(scoped_refptr<UsbDevice> device) : device_(device) {
    name_ = DevicePermissionsManager::GetPermissionMessage(
        device->vendor_id(), device->product_id(),
        device->manufacturer_string(), device->product_string(),
        base::string16(),  // Serial number is displayed separately.
        true);
    serial_number_ = device->serial_number();
  }

  ~UsbDeviceInfo() override {}

  const scoped_refptr<UsbDevice>& device() const { return device_; }

 private:
  // TODO(reillyg): Convert this to a weak reference when UsbDevice has a
  // connected flag.
  scoped_refptr<UsbDevice> device_;
};

class UsbDevicePermissionsPrompt : public DevicePermissionsPrompt::Prompt,
                                   public device::UsbService::Observer {
 public:
  UsbDevicePermissionsPrompt(
      const Extension* extension,
      content::BrowserContext* context,
      bool multiple,
      const std::vector<UsbDeviceFilter>& filters,
      const DevicePermissionsPrompt::UsbDevicesCallback& callback)
      : Prompt(extension, context, multiple),
        filters_(filters),
        callback_(callback),
        service_observer_(this) {}

 private:
  ~UsbDevicePermissionsPrompt() override {}

  // DevicePermissionsPrompt::Prompt implementation:
  void SetObserver(
      DevicePermissionsPrompt::Prompt::Observer* observer) override {
    DevicePermissionsPrompt::Prompt::SetObserver(observer);

    if (observer) {
      UsbService* service = device::DeviceClient::Get()->GetUsbService();
      if (service && !service_observer_.IsObserving(service)) {
        service->GetDevices(
            base::Bind(&UsbDevicePermissionsPrompt::OnDevicesEnumerated, this));
        service_observer_.Add(service);
      }
    }
  }

  base::string16 GetHeading() const override {
    return l10n_util::GetStringUTF16(
        multiple() ? IDS_USB_DEVICE_PERMISSIONS_PROMPT_TITLE_MULTIPLE
                   : IDS_USB_DEVICE_PERMISSIONS_PROMPT_TITLE_SINGLE);
  }

  void Dismissed() override {
    DevicePermissionsManager* permissions_manager =
        DevicePermissionsManager::Get(browser_context());
    std::vector<scoped_refptr<UsbDevice>> devices;
    for (const DeviceInfo* device : devices_) {
      if (device->granted()) {
        const UsbDeviceInfo* usb_device =
            static_cast<const UsbDeviceInfo*>(device);
        devices.push_back(usb_device->device());
        if (permissions_manager) {
          permissions_manager->AllowUsbDevice(extension()->id(),
                                              usb_device->device());
        }
      }
    }
    DCHECK(multiple() || devices.size() <= 1);
    callback_.Run(devices);
    callback_.Reset();
  }

  // device::UsbService::Observer implementation:
  void OnDeviceAdded(scoped_refptr<UsbDevice> device) override {
    if (!(filters_.empty() || UsbDeviceFilter::MatchesAny(device, filters_))) {
      return;
    }

    scoped_ptr<DeviceInfo> device_info(new UsbDeviceInfo(device));
    device->CheckUsbAccess(
        base::Bind(&UsbDevicePermissionsPrompt::AddCheckedDevice, this,
                   base::Passed(&device_info)));
  }

  void OnDeviceRemoved(scoped_refptr<UsbDevice> device) override {
    for (auto it = devices_.begin(); it != devices_.end(); ++it) {
      const UsbDeviceInfo* entry = static_cast<const UsbDeviceInfo*>(*it);
      if (entry->device() == device) {
        devices_.erase(it);
        if (observer()) {
          observer()->OnDevicesChanged();
        }
        return;
      }
    }
  }

  void OnDevicesEnumerated(
      const std::vector<scoped_refptr<UsbDevice>>& devices) {
    for (const auto& device : devices) {
      OnDeviceAdded(device);
    }
  }

  std::vector<UsbDeviceFilter> filters_;
  DevicePermissionsPrompt::UsbDevicesCallback callback_;
  ScopedObserver<UsbService, UsbService::Observer> service_observer_;
};

class HidDeviceInfo : public DevicePermissionsPrompt::Prompt::DeviceInfo {
 public:
  HidDeviceInfo(scoped_refptr<device::HidDeviceInfo> device) : device_(device) {
    name_ = DevicePermissionsManager::GetPermissionMessage(
        device->vendor_id(), device->product_id(),
        base::string16(),  // HID devices include manufacturer in product name.
        base::UTF8ToUTF16(device->product_name()),
        base::string16(),  // Serial number is displayed separately.
        false);
    serial_number_ = base::UTF8ToUTF16(device->serial_number());
  }

  ~HidDeviceInfo() override {}

  const scoped_refptr<device::HidDeviceInfo>& device() const { return device_; }

 private:
  scoped_refptr<device::HidDeviceInfo> device_;
};

class HidDevicePermissionsPrompt : public DevicePermissionsPrompt::Prompt,
                                   public device::HidService::Observer {
 public:
  HidDevicePermissionsPrompt(
      const Extension* extension,
      content::BrowserContext* context,
      bool multiple,
      const std::vector<HidDeviceFilter>& filters,
      const DevicePermissionsPrompt::HidDevicesCallback& callback)
      : Prompt(extension, context, multiple),
        filters_(filters),
        callback_(callback),
        service_observer_(this) {}

 private:
  ~HidDevicePermissionsPrompt() override {}

  // DevicePermissionsPrompt::Prompt implementation:
  void SetObserver(
      DevicePermissionsPrompt::Prompt::Observer* observer) override {
    DevicePermissionsPrompt::Prompt::SetObserver(observer);

    if (observer) {
      HidService* service = device::DeviceClient::Get()->GetHidService();
      if (service && !service_observer_.IsObserving(service)) {
        service->GetDevices(
            base::Bind(&HidDevicePermissionsPrompt::OnDevicesEnumerated, this));
        service_observer_.Add(service);
      }
    }
  }

  base::string16 GetHeading() const override {
    return l10n_util::GetStringUTF16(
        multiple() ? IDS_HID_DEVICE_PERMISSIONS_PROMPT_TITLE_MULTIPLE
                   : IDS_HID_DEVICE_PERMISSIONS_PROMPT_TITLE_SINGLE);
  }

  void Dismissed() override {
    DevicePermissionsManager* permissions_manager =
        DevicePermissionsManager::Get(browser_context());
    std::vector<scoped_refptr<device::HidDeviceInfo>> devices;
    for (const DeviceInfo* device : devices_) {
      if (device->granted()) {
        const HidDeviceInfo* hid_device =
            static_cast<const HidDeviceInfo*>(device);
        devices.push_back(hid_device->device());
        if (permissions_manager) {
          permissions_manager->AllowHidDevice(extension()->id(),
                                              hid_device->device());
        }
      }
    }
    DCHECK(multiple() || devices.size() <= 1);
    callback_.Run(devices);
    callback_.Reset();
  }

  // device::HidService::Observer implementation:
  void OnDeviceAdded(scoped_refptr<device::HidDeviceInfo> device) override {
    if (HasUnprotectedCollections(device) &&
        (filters_.empty() || HidDeviceFilter::MatchesAny(device, filters_))) {
      scoped_ptr<DeviceInfo> device_info(new HidDeviceInfo(device));
#if defined(OS_CHROMEOS)
      chromeos::PermissionBrokerClient* client =
          chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient();
      DCHECK(client) << "Could not get permission broker client.";
      client->CheckPathAccess(
          device->device_id(),
          base::Bind(&HidDevicePermissionsPrompt::AddCheckedDevice, this,
                     base::Passed(&device_info)));
#else
      AddCheckedDevice(device_info.Pass(), true);
#endif  // defined(OS_CHROMEOS)
    }
  }

  void OnDeviceRemoved(scoped_refptr<device::HidDeviceInfo> device) override {
    for (auto it = devices_.begin(); it != devices_.end(); ++it) {
      const HidDeviceInfo* entry = static_cast<const HidDeviceInfo*>(*it);
      if (entry->device() == device) {
        devices_.erase(it);
        if (observer()) {
          observer()->OnDevicesChanged();
        }
        return;
      }
    }
  }

  void OnDevicesEnumerated(
      const std::vector<scoped_refptr<device::HidDeviceInfo>>& devices) {
    for (const auto& device : devices) {
      OnDeviceAdded(device);
    }
  }

  bool HasUnprotectedCollections(scoped_refptr<device::HidDeviceInfo> device) {
    for (const auto& collection : device->collections()) {
      if (!collection.usage.IsProtected()) {
        return true;
      }
    }
    return false;
  }

  std::vector<HidDeviceFilter> filters_;
  DevicePermissionsPrompt::HidDevicesCallback callback_;
  ScopedObserver<HidService, HidService::Observer> service_observer_;
};

}  // namespace

DevicePermissionsPrompt::Prompt::DeviceInfo::DeviceInfo() {
}

DevicePermissionsPrompt::Prompt::DeviceInfo::~DeviceInfo() {
}

DevicePermissionsPrompt::Prompt::Observer::~Observer() {
}

DevicePermissionsPrompt::Prompt::Prompt(const Extension* extension,
                                        content::BrowserContext* context,
                                        bool multiple)
    : extension_(extension), browser_context_(context), multiple_(multiple) {
}

void DevicePermissionsPrompt::Prompt::SetObserver(Observer* observer) {
  observer_ = observer;
}

base::string16 DevicePermissionsPrompt::Prompt::GetPromptMessage() const {
  return l10n_util::GetStringFUTF16(multiple_
                                        ? IDS_DEVICE_PERMISSIONS_PROMPT_MULTIPLE
                                        : IDS_DEVICE_PERMISSIONS_PROMPT_SINGLE,
                                    base::UTF8ToUTF16(extension_->name()));
}

base::string16 DevicePermissionsPrompt::Prompt::GetDeviceName(
    size_t index) const {
  DCHECK_LT(index, devices_.size());
  return devices_[index]->name();
}

base::string16 DevicePermissionsPrompt::Prompt::GetDeviceSerialNumber(
    size_t index) const {
  DCHECK_LT(index, devices_.size());
  return devices_[index]->serial_number();
}

void DevicePermissionsPrompt::Prompt::GrantDevicePermission(size_t index) {
  DCHECK_LT(index, devices_.size());
  devices_[index]->set_granted();
}

DevicePermissionsPrompt::Prompt::~Prompt() {
}

void DevicePermissionsPrompt::Prompt::AddCheckedDevice(
    scoped_ptr<DeviceInfo> device,
    bool allowed) {
  if (allowed) {
    devices_.push_back(device.Pass());
    if (observer_) {
      observer_->OnDevicesChanged();
    }
  }
}

DevicePermissionsPrompt::DevicePermissionsPrompt(
    content::WebContents* web_contents)
    : web_contents_(web_contents) {
}

DevicePermissionsPrompt::~DevicePermissionsPrompt() {
}

void DevicePermissionsPrompt::AskForUsbDevices(
    const Extension* extension,
    content::BrowserContext* context,
    bool multiple,
    const std::vector<UsbDeviceFilter>& filters,
    const UsbDevicesCallback& callback) {
  prompt_ = new UsbDevicePermissionsPrompt(extension, context, multiple,
                                           filters, callback);
  ShowDialog();
}

void DevicePermissionsPrompt::AskForHidDevices(
    const Extension* extension,
    content::BrowserContext* context,
    bool multiple,
    const std::vector<HidDeviceFilter>& filters,
    const HidDevicesCallback& callback) {
  prompt_ = new HidDevicePermissionsPrompt(extension, context, multiple,
                                           filters, callback);
  ShowDialog();
}

}  // namespace extensions
<commit_msg>Check HID access by device node path instead of sysfs path.<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 "extensions/browser/api/device_permissions_prompt.h"

#include "base/bind.h"
#include "base/scoped_observer.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "device/core/device_client.h"
#include "device/hid/hid_device_filter.h"
#include "device/hid/hid_device_info.h"
#include "device/hid/hid_service.h"
#include "device/usb/usb_device.h"
#include "device/usb/usb_device_filter.h"
#include "device/usb/usb_ids.h"
#include "device/usb/usb_service.h"
#include "extensions/browser/api/device_permissions_manager.h"
#include "extensions/common/extension.h"
#include "extensions/strings/grit/extensions_strings.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(OS_CHROMEOS)
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/permission_broker_client.h"
#include "device/hid/hid_device_info_linux.h"
#endif  // defined(OS_CHROMEOS)

using device::HidDeviceFilter;
using device::HidService;
using device::UsbDevice;
using device::UsbDeviceFilter;
using device::UsbService;

namespace extensions {

namespace {

class UsbDeviceInfo : public DevicePermissionsPrompt::Prompt::DeviceInfo {
 public:
  UsbDeviceInfo(scoped_refptr<UsbDevice> device) : device_(device) {
    name_ = DevicePermissionsManager::GetPermissionMessage(
        device->vendor_id(), device->product_id(),
        device->manufacturer_string(), device->product_string(),
        base::string16(),  // Serial number is displayed separately.
        true);
    serial_number_ = device->serial_number();
  }

  ~UsbDeviceInfo() override {}

  const scoped_refptr<UsbDevice>& device() const { return device_; }

 private:
  // TODO(reillyg): Convert this to a weak reference when UsbDevice has a
  // connected flag.
  scoped_refptr<UsbDevice> device_;
};

class UsbDevicePermissionsPrompt : public DevicePermissionsPrompt::Prompt,
                                   public device::UsbService::Observer {
 public:
  UsbDevicePermissionsPrompt(
      const Extension* extension,
      content::BrowserContext* context,
      bool multiple,
      const std::vector<UsbDeviceFilter>& filters,
      const DevicePermissionsPrompt::UsbDevicesCallback& callback)
      : Prompt(extension, context, multiple),
        filters_(filters),
        callback_(callback),
        service_observer_(this) {}

 private:
  ~UsbDevicePermissionsPrompt() override {}

  // DevicePermissionsPrompt::Prompt implementation:
  void SetObserver(
      DevicePermissionsPrompt::Prompt::Observer* observer) override {
    DevicePermissionsPrompt::Prompt::SetObserver(observer);

    if (observer) {
      UsbService* service = device::DeviceClient::Get()->GetUsbService();
      if (service && !service_observer_.IsObserving(service)) {
        service->GetDevices(
            base::Bind(&UsbDevicePermissionsPrompt::OnDevicesEnumerated, this));
        service_observer_.Add(service);
      }
    }
  }

  base::string16 GetHeading() const override {
    return l10n_util::GetStringUTF16(
        multiple() ? IDS_USB_DEVICE_PERMISSIONS_PROMPT_TITLE_MULTIPLE
                   : IDS_USB_DEVICE_PERMISSIONS_PROMPT_TITLE_SINGLE);
  }

  void Dismissed() override {
    DevicePermissionsManager* permissions_manager =
        DevicePermissionsManager::Get(browser_context());
    std::vector<scoped_refptr<UsbDevice>> devices;
    for (const DeviceInfo* device : devices_) {
      if (device->granted()) {
        const UsbDeviceInfo* usb_device =
            static_cast<const UsbDeviceInfo*>(device);
        devices.push_back(usb_device->device());
        if (permissions_manager) {
          permissions_manager->AllowUsbDevice(extension()->id(),
                                              usb_device->device());
        }
      }
    }
    DCHECK(multiple() || devices.size() <= 1);
    callback_.Run(devices);
    callback_.Reset();
  }

  // device::UsbService::Observer implementation:
  void OnDeviceAdded(scoped_refptr<UsbDevice> device) override {
    if (!(filters_.empty() || UsbDeviceFilter::MatchesAny(device, filters_))) {
      return;
    }

    scoped_ptr<DeviceInfo> device_info(new UsbDeviceInfo(device));
    device->CheckUsbAccess(
        base::Bind(&UsbDevicePermissionsPrompt::AddCheckedDevice, this,
                   base::Passed(&device_info)));
  }

  void OnDeviceRemoved(scoped_refptr<UsbDevice> device) override {
    for (auto it = devices_.begin(); it != devices_.end(); ++it) {
      const UsbDeviceInfo* entry = static_cast<const UsbDeviceInfo*>(*it);
      if (entry->device() == device) {
        devices_.erase(it);
        if (observer()) {
          observer()->OnDevicesChanged();
        }
        return;
      }
    }
  }

  void OnDevicesEnumerated(
      const std::vector<scoped_refptr<UsbDevice>>& devices) {
    for (const auto& device : devices) {
      OnDeviceAdded(device);
    }
  }

  std::vector<UsbDeviceFilter> filters_;
  DevicePermissionsPrompt::UsbDevicesCallback callback_;
  ScopedObserver<UsbService, UsbService::Observer> service_observer_;
};

class HidDeviceInfo : public DevicePermissionsPrompt::Prompt::DeviceInfo {
 public:
  HidDeviceInfo(scoped_refptr<device::HidDeviceInfo> device) : device_(device) {
    name_ = DevicePermissionsManager::GetPermissionMessage(
        device->vendor_id(), device->product_id(),
        base::string16(),  // HID devices include manufacturer in product name.
        base::UTF8ToUTF16(device->product_name()),
        base::string16(),  // Serial number is displayed separately.
        false);
    serial_number_ = base::UTF8ToUTF16(device->serial_number());
  }

  ~HidDeviceInfo() override {}

  const scoped_refptr<device::HidDeviceInfo>& device() const { return device_; }

 private:
  scoped_refptr<device::HidDeviceInfo> device_;
};

class HidDevicePermissionsPrompt : public DevicePermissionsPrompt::Prompt,
                                   public device::HidService::Observer {
 public:
  HidDevicePermissionsPrompt(
      const Extension* extension,
      content::BrowserContext* context,
      bool multiple,
      const std::vector<HidDeviceFilter>& filters,
      const DevicePermissionsPrompt::HidDevicesCallback& callback)
      : Prompt(extension, context, multiple),
        filters_(filters),
        callback_(callback),
        service_observer_(this) {}

 private:
  ~HidDevicePermissionsPrompt() override {}

  // DevicePermissionsPrompt::Prompt implementation:
  void SetObserver(
      DevicePermissionsPrompt::Prompt::Observer* observer) override {
    DevicePermissionsPrompt::Prompt::SetObserver(observer);

    if (observer) {
      HidService* service = device::DeviceClient::Get()->GetHidService();
      if (service && !service_observer_.IsObserving(service)) {
        service->GetDevices(
            base::Bind(&HidDevicePermissionsPrompt::OnDevicesEnumerated, this));
        service_observer_.Add(service);
      }
    }
  }

  base::string16 GetHeading() const override {
    return l10n_util::GetStringUTF16(
        multiple() ? IDS_HID_DEVICE_PERMISSIONS_PROMPT_TITLE_MULTIPLE
                   : IDS_HID_DEVICE_PERMISSIONS_PROMPT_TITLE_SINGLE);
  }

  void Dismissed() override {
    DevicePermissionsManager* permissions_manager =
        DevicePermissionsManager::Get(browser_context());
    std::vector<scoped_refptr<device::HidDeviceInfo>> devices;
    for (const DeviceInfo* device : devices_) {
      if (device->granted()) {
        const HidDeviceInfo* hid_device =
            static_cast<const HidDeviceInfo*>(device);
        devices.push_back(hid_device->device());
        if (permissions_manager) {
          permissions_manager->AllowHidDevice(extension()->id(),
                                              hid_device->device());
        }
      }
    }
    DCHECK(multiple() || devices.size() <= 1);
    callback_.Run(devices);
    callback_.Reset();
  }

  // device::HidService::Observer implementation:
  void OnDeviceAdded(scoped_refptr<device::HidDeviceInfo> device) override {
    if (HasUnprotectedCollections(device) &&
        (filters_.empty() || HidDeviceFilter::MatchesAny(device, filters_))) {
      scoped_ptr<DeviceInfo> device_info(new HidDeviceInfo(device));
#if defined(OS_CHROMEOS)
      chromeos::PermissionBrokerClient* client =
          chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient();
      DCHECK(client) << "Could not get permission broker client.";
      device::HidDeviceInfoLinux* linux_device_info =
          static_cast<device::HidDeviceInfoLinux*>(device.get());
      client->CheckPathAccess(
          linux_device_info->device_node(),
          base::Bind(&HidDevicePermissionsPrompt::AddCheckedDevice, this,
                     base::Passed(&device_info)));
#else
      AddCheckedDevice(device_info.Pass(), true);
#endif  // defined(OS_CHROMEOS)
    }
  }

  void OnDeviceRemoved(scoped_refptr<device::HidDeviceInfo> device) override {
    for (auto it = devices_.begin(); it != devices_.end(); ++it) {
      const HidDeviceInfo* entry = static_cast<const HidDeviceInfo*>(*it);
      if (entry->device() == device) {
        devices_.erase(it);
        if (observer()) {
          observer()->OnDevicesChanged();
        }
        return;
      }
    }
  }

  void OnDevicesEnumerated(
      const std::vector<scoped_refptr<device::HidDeviceInfo>>& devices) {
    for (const auto& device : devices) {
      OnDeviceAdded(device);
    }
  }

  bool HasUnprotectedCollections(scoped_refptr<device::HidDeviceInfo> device) {
    for (const auto& collection : device->collections()) {
      if (!collection.usage.IsProtected()) {
        return true;
      }
    }
    return false;
  }

  std::vector<HidDeviceFilter> filters_;
  DevicePermissionsPrompt::HidDevicesCallback callback_;
  ScopedObserver<HidService, HidService::Observer> service_observer_;
};

}  // namespace

DevicePermissionsPrompt::Prompt::DeviceInfo::DeviceInfo() {
}

DevicePermissionsPrompt::Prompt::DeviceInfo::~DeviceInfo() {
}

DevicePermissionsPrompt::Prompt::Observer::~Observer() {
}

DevicePermissionsPrompt::Prompt::Prompt(const Extension* extension,
                                        content::BrowserContext* context,
                                        bool multiple)
    : extension_(extension), browser_context_(context), multiple_(multiple) {
}

void DevicePermissionsPrompt::Prompt::SetObserver(Observer* observer) {
  observer_ = observer;
}

base::string16 DevicePermissionsPrompt::Prompt::GetPromptMessage() const {
  return l10n_util::GetStringFUTF16(multiple_
                                        ? IDS_DEVICE_PERMISSIONS_PROMPT_MULTIPLE
                                        : IDS_DEVICE_PERMISSIONS_PROMPT_SINGLE,
                                    base::UTF8ToUTF16(extension_->name()));
}

base::string16 DevicePermissionsPrompt::Prompt::GetDeviceName(
    size_t index) const {
  DCHECK_LT(index, devices_.size());
  return devices_[index]->name();
}

base::string16 DevicePermissionsPrompt::Prompt::GetDeviceSerialNumber(
    size_t index) const {
  DCHECK_LT(index, devices_.size());
  return devices_[index]->serial_number();
}

void DevicePermissionsPrompt::Prompt::GrantDevicePermission(size_t index) {
  DCHECK_LT(index, devices_.size());
  devices_[index]->set_granted();
}

DevicePermissionsPrompt::Prompt::~Prompt() {
}

void DevicePermissionsPrompt::Prompt::AddCheckedDevice(
    scoped_ptr<DeviceInfo> device,
    bool allowed) {
  if (allowed) {
    devices_.push_back(device.Pass());
    if (observer_) {
      observer_->OnDevicesChanged();
    }
  }
}

DevicePermissionsPrompt::DevicePermissionsPrompt(
    content::WebContents* web_contents)
    : web_contents_(web_contents) {
}

DevicePermissionsPrompt::~DevicePermissionsPrompt() {
}

void DevicePermissionsPrompt::AskForUsbDevices(
    const Extension* extension,
    content::BrowserContext* context,
    bool multiple,
    const std::vector<UsbDeviceFilter>& filters,
    const UsbDevicesCallback& callback) {
  prompt_ = new UsbDevicePermissionsPrompt(extension, context, multiple,
                                           filters, callback);
  ShowDialog();
}

void DevicePermissionsPrompt::AskForHidDevices(
    const Extension* extension,
    content::BrowserContext* context,
    bool multiple,
    const std::vector<HidDeviceFilter>& filters,
    const HidDevicesCallback& callback) {
  prompt_ = new HidDevicePermissionsPrompt(extension, context, multiple,
                                           filters, callback);
  ShowDialog();
}

}  // namespace extensions
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2004,2006 Matthias Kretz <kretz@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.

*/

#include "backendselection.h"

#include <kservicetypeprofile.h>
#include <dcopclient.h>
#include <kservicetypetrader.h>
#include <ksimpleconfig.h>
#include <QStringList>
#include <QListWidgetItem>
#include <kapplication.h>
#include <kicon.h>
#include <QList>

BackendSelection::BackendSelection( QWidget* parent )
	: QWidget( parent )
{
	setupUi( this );

	connect( m_select, SIGNAL( itemSelectionChanged() ),
			SLOT( selectionChanged() ) );
	//connect( m_website, SIGNAL( leftClickedURL( const QString & ) ),
			//kapp, SLOT( invokeBrowser( const QString & ) ) );
	connect( m_up, SIGNAL( clicked() ), SLOT( up() ) );
	connect( m_down, SIGNAL( clicked() ), SLOT( down() ) );
}

void BackendSelection::load()
{
	m_services.clear();
	m_select->clear();
	KServiceTypeProfile::clear();

        const KService::List offers = KServiceTypeTrader::self()->query( "PhononBackend",
			"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" );
	// the offers are already sorted for preference
        KService::List::const_iterator it = offers.begin();
        const KService::List::const_iterator end = offers.end();
	for( ; it != end; ++it )
	{
		KService::Ptr service = *it;
		m_select->addItem( service->name() );
		m_services[ service->name() ] = service;
	}
	m_select->setItemSelected( m_select->item( 0 ), true );
}

void BackendSelection::save()
{
	// save to profilerc
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
			config.deleteGroup( *it );
	}
	unsigned int count = m_select->count();
	for( unsigned int i = 0; i < count; ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		KService::Ptr service = m_services[ item->text() ];
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", service->storageId() );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", count - i );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
	KService::rebuildKSycoca( this );

	kapp->dcopClient()->emitDCOPSignal( "phononBackendChanged()", QByteArray() );
}

void BackendSelection::defaults()
{
	// XXX: hack, I don't know how to get the initalPreference without
	// reading it all manually
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	QStringList apps;
	QList<int> pref;
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
		{
			apps.append( config.readEntry( "Application" ) );
			pref.append( config.readEntry( "Preference", int( 0 ) ) );
			config.deleteGroup( *it );
		}
	}
	config.sync();
	load();
	for( int i = 0; i < apps.count(); ++i )
	{
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", apps[ i ] );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", pref[ i ] );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
}

void BackendSelection::selectionChanged()
{
	KService::Ptr service;
	for( int i = 0; i < m_select->count(); ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		if( m_select->isItemSelected( item ) )
		{
			service = m_services[ item->text() ];
			break;
		}
	}
	m_icon->setPixmap( KIcon( service->icon() ).pixmap( 32 ) );
	m_name->setText( service->name() );
	m_comment->setText( service->comment() );
	m_website->setText( service->property( "X-KDE-PhononBackendInfo-Website" ).toString() );
	//m_website->setURL( m_website->text() );
	m_version->setText( service->property( "X-KDE-PhononBackendInfo-Version" ).toString() );
}

void BackendSelection::up()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row > 0 )
		{
			QListWidgetItem* taken = m_select->takeItem( row - 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

void BackendSelection::down()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row + 1 < m_select->count() )
		{
			QListWidgetItem* taken = m_select->takeItem( row + 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

#include "backendselection.moc"

// vim: sw=4 ts=4 noet
<commit_msg>The progress dialog looks fancy, but there's no need to rebuild ksycoca when profilerc changes, the profile isn't stored in ksycoca. Anyway I'll provide public API for writing to profilerc.<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2004,2006 Matthias Kretz <kretz@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2
    as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.

*/

#include "backendselection.h"

#include <kservicetypeprofile.h>
#include <dcopclient.h>
#include <kservicetypetrader.h>
#include <ksimpleconfig.h>
#include <QStringList>
#include <QListWidgetItem>
#include <kapplication.h>
#include <kicon.h>
#include <QList>

BackendSelection::BackendSelection( QWidget* parent )
	: QWidget( parent )
{
	setupUi( this );

	connect( m_select, SIGNAL( itemSelectionChanged() ),
			SLOT( selectionChanged() ) );
	//connect( m_website, SIGNAL( leftClickedURL( const QString & ) ),
			//kapp, SLOT( invokeBrowser( const QString & ) ) );
	connect( m_up, SIGNAL( clicked() ), SLOT( up() ) );
	connect( m_down, SIGNAL( clicked() ), SLOT( down() ) );
}

void BackendSelection::load()
{
	m_services.clear();
	m_select->clear();
	KServiceTypeProfile::clear();

        const KService::List offers = KServiceTypeTrader::self()->query( "PhononBackend",
			"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1" );
	// the offers are already sorted for preference
        KService::List::const_iterator it = offers.begin();
        const KService::List::const_iterator end = offers.end();
	for( ; it != end; ++it )
	{
		KService::Ptr service = *it;
		m_select->addItem( service->name() );
		m_services[ service->name() ] = service;
	}
	m_select->setItemSelected( m_select->item( 0 ), true );
}

void BackendSelection::save()
{
	// save to profilerc
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
			config.deleteGroup( *it );
	}
	unsigned int count = m_select->count();
	for( unsigned int i = 0; i < count; ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		KService::Ptr service = m_services[ item->text() ];
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", service->storageId() );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", count - i );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
	KServiceTypeProfile::clear();

	kapp->dcopClient()->emitDCOPSignal( "phononBackendChanged()", QByteArray() );
}

void BackendSelection::defaults()
{
	// XXX: hack, I don't know how to get the initalPreference without
	// reading it all manually
	KSimpleConfig config( "profilerc" );
	QStringList grouplist = config.groupList();
	QStringList::Iterator it = grouplist.begin();
	QStringList::Iterator end = grouplist.end();
	QStringList apps;
	QList<int> pref;
	for( ; it != end; ++it )
	{
		config.setGroup( *it );
		if( config.readEntry( "ServiceType" ) == "PhononBackend" )
		{
			apps.append( config.readEntry( "Application" ) );
			pref.append( config.readEntry( "Preference", int( 0 ) ) );
			config.deleteGroup( *it );
		}
	}
	config.sync();
	load();
	for( int i = 0; i < apps.count(); ++i )
	{
		config.setGroup( "PhononBackend" + QString( " - %1" ).arg( i ) );
		config.writeEntry( "AllowAsDefault", true );
		config.writeEntry( "Application", apps[ i ] );
		config.writeEntry( "GenericServiceType", "PhononBackend" );
		config.writeEntry( "Preference", pref[ i ] );
		config.writeEntry( "ServiceType", "PhononBackend" );
	}
	config.sync();
}

void BackendSelection::selectionChanged()
{
	KService::Ptr service;
	for( int i = 0; i < m_select->count(); ++i )
	{
		QListWidgetItem* item = m_select->item( i );
		if( m_select->isItemSelected( item ) )
		{
			service = m_services[ item->text() ];
			break;
		}
	}
	m_icon->setPixmap( KIcon( service->icon() ).pixmap( 32 ) );
	m_name->setText( service->name() );
	m_comment->setText( service->comment() );
	m_website->setText( service->property( "X-KDE-PhononBackendInfo-Website" ).toString() );
	//m_website->setURL( m_website->text() );
	m_version->setText( service->property( "X-KDE-PhononBackendInfo-Version" ).toString() );
}

void BackendSelection::up()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row > 0 )
		{
			QListWidgetItem* taken = m_select->takeItem( row - 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

void BackendSelection::down()
{
	QList<QListWidgetItem*> selectedList = m_select->selectedItems();
	foreach( QListWidgetItem* selected, selectedList )
	{
		int row = m_select->row( selected );
		if( row + 1 < m_select->count() )
		{
			QListWidgetItem* taken = m_select->takeItem( row + 1 );
			m_select->insertItem( row, taken );
			emit changed();
		}
	}
}

#include "backendselection.moc"

// vim: sw=4 ts=4 noet
<|endoftext|>


<commit_before>#include <iostream>

#include <stdexcept>
#include <unordered_map>

#include "windowswindow.hh"
#include "windowsopenglcontext.hh"

#define FILE_EXIT_OPTION 9001
static char appName[] = "Test Application";

using System::KeyCode;

class KeyMap : public std::unordered_map<WPARAM, System::KeyCode> {
public:
	KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() {
		(*this)[VK_PRIOR]   = KeyCode::KeyPageUp;
		(*this)[VK_NEXT]    = KeyCode::KeyPageDown;
		(*this)[VK_END]     = KeyCode::KeyEnd;
		(*this)[VK_HOME]    = KeyCode::KeyHome;
		(*this)[VK_INSERT]  = KeyCode::KeyInsert;
		(*this)[VK_DELETE]  = KeyCode::KeyDelete;

		(*this)[VK_RIGHT]   = KeyCode::KeyRightArrow;
		(*this)[VK_DOWN]    = KeyCode::KeyDownArrow;
		(*this)[VK_LEFT]    = KeyCode::KeyLeftArrow;
		(*this)[VK_UP]      = KeyCode::KeyUpArrow;

		(*this)[VK_ESCAPE]  = KeyCode::KeyEscape;
		(*this)[VK_TAB]     = KeyCode::KeyTab;
		(*this)[VK_SHIFT]   = KeyCode::KeyShift;
		(*this)[VK_MENU]    = KeyCode::KeyAlt;
		(*this)[VK_CONTROL] = KeyCode::KeyControl;
		(*this)[VK_CAPITAL] = KeyCode::KeyCapsLock;

		(*this)[VK_RCONTROL] = KeyCode::KeyRightControl;
		(*this)[VK_LCONTROL] = KeyCode::KeyLeftControl;
		(*this)[VK_RSHIFT]   = KeyCode::KeyRightShift;
		(*this)[VK_LSHIFT]   = KeyCode::KeyLeftShift;

		(*this)[VK_BACK]    = KeyCode::KeyBackspace;
		(*this)[VK_RETURN]  = KeyCode::KeyEnter;
		(*this)[VK_SPACE]   = KeyCode::KeySpace;

		(*this)[0x30]       = KeyCode::Key0;
		(*this)[0x31]       = KeyCode::Key1;
		(*this)[0x32]       = KeyCode::Key2;
		(*this)[0x33]       = KeyCode::Key3;
		(*this)[0x34]       = KeyCode::Key4;
		(*this)[0x35]       = KeyCode::Key5;
		(*this)[0x36]       = KeyCode::Key6;
		(*this)[0x37]       = KeyCode::Key7;
		(*this)[0x38]       = KeyCode::Key8;
		(*this)[0x39]       = KeyCode::Key9;

		(*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0;
		(*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1;
		(*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2;
		(*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3;
		(*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4;
		(*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5;
		(*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6;
		(*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7;
		(*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8;
		(*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9;

		(*this)[VK_MULTIPLY] = KeyCode::KeyMultiply;
		(*this)[VK_ADD]      = KeyCode::KeyPlus;
		(*this)[VK_SUBTRACT] = KeyCode::KeyMinus;
		(*this)[VK_DIVIDE]   = KeyCode::KeyDivide;
		(*this)[VK_DECIMAL]  = KeyCode::KeyDecimal;

		(*this)[0x41]       = KeyCode::KeyA;
		(*this)[0x42]       = KeyCode::KeyB;
		(*this)[0x43]       = KeyCode::KeyC;
		(*this)[0x44]       = KeyCode::KeyD;
		(*this)[0x45]       = KeyCode::KeyE;
		(*this)[0x46]       = KeyCode::KeyF;
		(*this)[0x47]       = KeyCode::KeyG;
		(*this)[0x48]       = KeyCode::KeyH;
		(*this)[0x49]       = KeyCode::KeyI;
		(*this)[0x4A]       = KeyCode::KeyJ;
		(*this)[0x4B]       = KeyCode::KeyK;
		(*this)[0x4C]       = KeyCode::KeyL;
		(*this)[0x4D]       = KeyCode::KeyM;
		(*this)[0x4E]       = KeyCode::KeyN;
		(*this)[0x4F]       = KeyCode::KeyO;
		(*this)[0x50]       = KeyCode::KeyP;
		(*this)[0x51]       = KeyCode::KeyQ;
		(*this)[0x52]       = KeyCode::KeyR;
		(*this)[0x53]       = KeyCode::KeyS;
		(*this)[0x54]       = KeyCode::KeyT;
		(*this)[0x55]       = KeyCode::KeyU;
		(*this)[0x56]       = KeyCode::KeyV;
		(*this)[0x57]       = KeyCode::KeyW;
		(*this)[0x59]       = KeyCode::KeyY;
		(*this)[0x5A]       = KeyCode::KeyZ;
	}
};

static KeyMap keyMap;
static std::unordered_map<HWND, WindowsWindow*> windowMap;

WindowsWindow::WindowsWindow(Framework::ApplicationContext *applicationContext, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow)
	: m_applicationContext(applicationContext), m_controller(controller), m_openGLContext(NULL)
{
	WNDCLASSEX windowClass;

	windowClass.cbSize        = sizeof(WNDCLASSEX);
	windowClass.style         = CS_VREDRAW | CS_HREDRAW;
	windowClass.lpfnWndProc   = WndProc;
	windowClass.cbClsExtra    = 0;
	windowClass.cbWndExtra    = 0;
	windowClass.hInstance     = processInstance;
	windowClass.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	windowClass.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
	windowClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
	windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
	windowClass.lpszClassName = appName;
	windowClass.lpszMenuName  = NULL;

	RegisterClassEx(&windowClass);

	m_windowHandle = CreateWindow(appName, m_applicationContext->GetState()->windowName, WS_OVERLAPPEDWINDOW, -1920, 0, 800, 600, NULL, NULL, processInstance, NULL);

	windowMap[m_windowHandle] = this;

	ShowWindow(m_windowHandle, commandShow);
	UpdateWindow(m_windowHandle);
}

WindowsWindow::~WindowsWindow() {
	windowMap[m_windowHandle] = NULL;
}

int WindowsWindow::DoMessageLoop() {
	MSG message;

	Ready();

	while (GetMessage(&message, NULL, 0, 0))
	{
		TranslateMessage(&message);
		DispatchMessage(&message);

		// Don't do this here?
		if (m_applicationContext->ShouldDestroyWindow())
			Destroy();
	}

	return message.wParam;
}

void WindowsWindow::Destroy()
{
	DestroyWindow(m_windowHandle);
}

void WindowsWindow::Ready()
{
	m_controller->OnWindowReady();
}

void WindowsWindow::Close()
{
	m_controller->OnWindowClose();
}

void WindowsWindow::KeyDown(WPARAM key)
{
	m_controller->OnKeyDown(keyMap[key]);
}

void WindowsWindow::KeyUp(WPARAM key)
{
	m_controller->OnKeyUp(keyMap[key]);
}

LRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam) {
	PAINTSTRUCT ps;
	HDC hdc;
	HMENU fileMenuHandle, mainMenuHandle;

	switch(message)
	{
	case WM_ACTIVATEAPP:
		std::cout << "WndProc handling WM_ACTIVATEAPP: " << wparam << " : " << lparam << std::endl;
		break;

	case WM_KEYDOWN:
		windowMap[windowHandle]->KeyDown(wparam);
		return 0;

	case WM_KEYUP:
		windowMap[windowHandle]->KeyUp(wparam);
		return 0;

	case WM_PAINT:
		hdc = BeginPaint(windowHandle, &ps);
		TextOut(hdc, 100, 100, "Hello world", 11);
		EndPaint(windowHandle, &ps);
		return 0;

	case WM_CLOSE:
		windowMap[windowHandle]->Close();
		return 0;

	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;

	default:
		return DefWindowProc(windowHandle, message, wparam, lparam);
	}
}
<commit_msg>Remove windows debug messages<commit_after>#include <stdexcept>
#include <unordered_map>

#include "windowswindow.hh"
#include "windowsopenglcontext.hh"

#define FILE_EXIT_OPTION 9001
static char appName[] = "Test Application";

using System::KeyCode;

class KeyMap : public std::unordered_map<WPARAM, System::KeyCode> {
public:
	KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() {
		(*this)[VK_PRIOR]   = KeyCode::KeyPageUp;
		(*this)[VK_NEXT]    = KeyCode::KeyPageDown;
		(*this)[VK_END]     = KeyCode::KeyEnd;
		(*this)[VK_HOME]    = KeyCode::KeyHome;
		(*this)[VK_INSERT]  = KeyCode::KeyInsert;
		(*this)[VK_DELETE]  = KeyCode::KeyDelete;

		(*this)[VK_RIGHT]   = KeyCode::KeyRightArrow;
		(*this)[VK_DOWN]    = KeyCode::KeyDownArrow;
		(*this)[VK_LEFT]    = KeyCode::KeyLeftArrow;
		(*this)[VK_UP]      = KeyCode::KeyUpArrow;

		(*this)[VK_ESCAPE]  = KeyCode::KeyEscape;
		(*this)[VK_TAB]     = KeyCode::KeyTab;
		(*this)[VK_SHIFT]   = KeyCode::KeyShift;
		(*this)[VK_MENU]    = KeyCode::KeyAlt;
		(*this)[VK_CONTROL] = KeyCode::KeyControl;
		(*this)[VK_CAPITAL] = KeyCode::KeyCapsLock;

		(*this)[VK_RCONTROL] = KeyCode::KeyRightControl;
		(*this)[VK_LCONTROL] = KeyCode::KeyLeftControl;
		(*this)[VK_RSHIFT]   = KeyCode::KeyRightShift;
		(*this)[VK_LSHIFT]   = KeyCode::KeyLeftShift;

		(*this)[VK_BACK]    = KeyCode::KeyBackspace;
		(*this)[VK_RETURN]  = KeyCode::KeyEnter;
		(*this)[VK_SPACE]   = KeyCode::KeySpace;

		(*this)[0x30]       = KeyCode::Key0;
		(*this)[0x31]       = KeyCode::Key1;
		(*this)[0x32]       = KeyCode::Key2;
		(*this)[0x33]       = KeyCode::Key3;
		(*this)[0x34]       = KeyCode::Key4;
		(*this)[0x35]       = KeyCode::Key5;
		(*this)[0x36]       = KeyCode::Key6;
		(*this)[0x37]       = KeyCode::Key7;
		(*this)[0x38]       = KeyCode::Key8;
		(*this)[0x39]       = KeyCode::Key9;

		(*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0;
		(*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1;
		(*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2;
		(*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3;
		(*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4;
		(*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5;
		(*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6;
		(*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7;
		(*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8;
		(*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9;

		(*this)[VK_MULTIPLY] = KeyCode::KeyMultiply;
		(*this)[VK_ADD]      = KeyCode::KeyPlus;
		(*this)[VK_SUBTRACT] = KeyCode::KeyMinus;
		(*this)[VK_DIVIDE]   = KeyCode::KeyDivide;
		(*this)[VK_DECIMAL]  = KeyCode::KeyDecimal;

		(*this)[0x41]       = KeyCode::KeyA;
		(*this)[0x42]       = KeyCode::KeyB;
		(*this)[0x43]       = KeyCode::KeyC;
		(*this)[0x44]       = KeyCode::KeyD;
		(*this)[0x45]       = KeyCode::KeyE;
		(*this)[0x46]       = KeyCode::KeyF;
		(*this)[0x47]       = KeyCode::KeyG;
		(*this)[0x48]       = KeyCode::KeyH;
		(*this)[0x49]       = KeyCode::KeyI;
		(*this)[0x4A]       = KeyCode::KeyJ;
		(*this)[0x4B]       = KeyCode::KeyK;
		(*this)[0x4C]       = KeyCode::KeyL;
		(*this)[0x4D]       = KeyCode::KeyM;
		(*this)[0x4E]       = KeyCode::KeyN;
		(*this)[0x4F]       = KeyCode::KeyO;
		(*this)[0x50]       = KeyCode::KeyP;
		(*this)[0x51]       = KeyCode::KeyQ;
		(*this)[0x52]       = KeyCode::KeyR;
		(*this)[0x53]       = KeyCode::KeyS;
		(*this)[0x54]       = KeyCode::KeyT;
		(*this)[0x55]       = KeyCode::KeyU;
		(*this)[0x56]       = KeyCode::KeyV;
		(*this)[0x57]       = KeyCode::KeyW;
		(*this)[0x59]       = KeyCode::KeyY;
		(*this)[0x5A]       = KeyCode::KeyZ;
	}
};

static KeyMap keyMap;
static std::unordered_map<HWND, WindowsWindow*> windowMap;

WindowsWindow::WindowsWindow(Framework::ApplicationContext *applicationContext, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow)
	: m_applicationContext(applicationContext), m_controller(controller), m_openGLContext(NULL)
{
	WNDCLASSEX windowClass;

	windowClass.cbSize        = sizeof(WNDCLASSEX);
	windowClass.style         = CS_VREDRAW | CS_HREDRAW;
	windowClass.lpfnWndProc   = WndProc;
	windowClass.cbClsExtra    = 0;
	windowClass.cbWndExtra    = 0;
	windowClass.hInstance     = processInstance;
	windowClass.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	windowClass.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
	windowClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
	windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
	windowClass.lpszClassName = appName;
	windowClass.lpszMenuName  = NULL;

	RegisterClassEx(&windowClass);

	m_windowHandle = CreateWindow(appName, m_applicationContext->GetState()->windowName, WS_OVERLAPPEDWINDOW, -1920, 0, 800, 600, NULL, NULL, processInstance, NULL);

	windowMap[m_windowHandle] = this;

	ShowWindow(m_windowHandle, commandShow);
	UpdateWindow(m_windowHandle);
}

WindowsWindow::~WindowsWindow() {
	windowMap[m_windowHandle] = NULL;
}

int WindowsWindow::DoMessageLoop() {
	MSG message;

	Ready();

	while (GetMessage(&message, NULL, 0, 0))
	{
		TranslateMessage(&message);
		DispatchMessage(&message);

		// Don't do this here?
		if (m_applicationContext->ShouldDestroyWindow())
			Destroy();
	}

	return message.wParam;
}

void WindowsWindow::Destroy()
{
	DestroyWindow(m_windowHandle);
}

void WindowsWindow::Ready()
{
	m_controller->OnWindowReady();
}

void WindowsWindow::Close()
{
	m_controller->OnWindowClose();
}

void WindowsWindow::KeyDown(WPARAM key)
{
	m_controller->OnKeyDown(keyMap[key]);
}

void WindowsWindow::KeyUp(WPARAM key)
{
	m_controller->OnKeyUp(keyMap[key]);
}

LRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam) {
	PAINTSTRUCT ps;
	HDC hdc;
	HMENU fileMenuHandle, mainMenuHandle;

	switch(message)
	{
	case WM_KEYDOWN:
		windowMap[windowHandle]->KeyDown(wparam);
		return 0;

	case WM_KEYUP:
		windowMap[windowHandle]->KeyUp(wparam);
		return 0;

	case WM_CLOSE:
		windowMap[windowHandle]->Close();
		return 0;

	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;

	default:
		return DefWindowProc(windowHandle, message, wparam, lparam);
	}
}
<|endoftext|>


<commit_before>// Copyright 2016 The RE2 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 <stddef.h>
#include <stdint.h>
#include <map>
#include <string>

#include "re2/re2.h"

using re2::StringPiece;
using std::string;

// NOT static, NOT signed.
uint8_t dummy = 0;

void Test(StringPiece pattern, const RE2::Options& options, StringPiece text) {
  RE2 re(pattern, options);
  if (!re.ok())
    return;

  // Don't waste time fuzzing high-size programs.
  // (They can cause bug reports due to fuzzer timeouts.)
  int size = re.ProgramSize();
  if (size > 9999)
    return;

  // Don't waste time fuzzing high-fanout programs.
  // (They can also cause bug reports due to fuzzer timeouts.)
  std::map<int, int> histogram;
  int fanout = re.ProgramFanout(&histogram);
  if (fanout > 9)
    return;

  StringPiece sp1, sp2, sp3, sp4;
  string s1, s2, s3, s4;
  int i1, i2, i3, i4;
  double d1, d2, d3, d4;

  RE2::FullMatch(text, re, &sp1, &sp2, &sp3, &sp4);
  RE2::PartialMatch(text, re, &s1, &s2, &s3, &s4);

  sp1 = sp2 = text;
  RE2::Consume(&sp1, re, &i1, &i2, &i3, &i4);
  RE2::FindAndConsume(&sp2, re, &d1, &d2, &d3, &d4);

  s3 = s4 = text.ToString();
  RE2::Replace(&s3, re, "");
  RE2::GlobalReplace(&s4, re, "");

  // Exercise some other API functionality.
  dummy += re.NumberOfCapturingGroups();
  dummy += RE2::QuoteMeta(pattern).size();
}

// Entry point for libFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size == 0 || size > 1024)
    return 0;

  // Crudely limit the use of \p and \P.
  int backslash_p = 0;
  for (size_t i = 0; i < size; i++) {
    if (data[i] == '\\' && i+1 < size && (data[i+1] == 'p' || data[i+1] == 'P'))
      backslash_p++;
  }
  if (backslash_p > 10)
    return 0;

  // The one-at-a-time hash by Bob Jenkins.
  uint32_t hash = 0;
  for (size_t i = 0; i < size; i++) {
    hash += data[i];
    hash += (hash << 10);
    hash ^= (hash >> 6);
  }
  hash += (hash << 3);
  hash ^= (hash >> 11);
  hash += (hash << 15);

  RE2::Options options;
  options.set_log_errors(false);
  options.set_max_mem(64 << 20);
  options.set_encoding(hash & 1 ? RE2::Options::EncodingLatin1
                                : RE2::Options::EncodingUTF8);
  options.set_posix_syntax(hash & 2);
  options.set_longest_match(hash & 4);
  options.set_literal(hash & 8);
  options.set_never_nl(hash & 16);
  options.set_dot_nl(hash & 32);
  options.set_never_capture(hash & 64);
  options.set_case_sensitive(hash & 128);
  options.set_perl_classes(hash & 256);
  options.set_word_boundary(hash & 512);
  options.set_one_line(hash & 1024);

  const char* ptr = reinterpret_cast<const char*>(data);
  int len = static_cast<int>(size);

  StringPiece pattern(ptr, len);
  StringPiece text(ptr, len);
  Test(pattern, options, text);

  return 0;
}
<commit_msg>Expand the comment on the \p and \P limit.<commit_after>// Copyright 2016 The RE2 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 <stddef.h>
#include <stdint.h>
#include <map>
#include <string>

#include "re2/re2.h"

using re2::StringPiece;
using std::string;

// NOT static, NOT signed.
uint8_t dummy = 0;

void Test(StringPiece pattern, const RE2::Options& options, StringPiece text) {
  RE2 re(pattern, options);
  if (!re.ok())
    return;

  // Don't waste time fuzzing high-size programs.
  // (They can cause bug reports due to fuzzer timeouts.)
  int size = re.ProgramSize();
  if (size > 9999)
    return;

  // Don't waste time fuzzing high-fanout programs.
  // (They can also cause bug reports due to fuzzer timeouts.)
  std::map<int, int> histogram;
  int fanout = re.ProgramFanout(&histogram);
  if (fanout > 9)
    return;

  StringPiece sp1, sp2, sp3, sp4;
  string s1, s2, s3, s4;
  int i1, i2, i3, i4;
  double d1, d2, d3, d4;

  RE2::FullMatch(text, re, &sp1, &sp2, &sp3, &sp4);
  RE2::PartialMatch(text, re, &s1, &s2, &s3, &s4);

  sp1 = sp2 = text;
  RE2::Consume(&sp1, re, &i1, &i2, &i3, &i4);
  RE2::FindAndConsume(&sp2, re, &d1, &d2, &d3, &d4);

  s3 = s4 = text.ToString();
  RE2::Replace(&s3, re, "");
  RE2::GlobalReplace(&s4, re, "");

  // Exercise some other API functionality.
  dummy += re.NumberOfCapturingGroups();
  dummy += RE2::QuoteMeta(pattern).size();
}

// Entry point for libFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  if (size == 0 || size > 1024)
    return 0;

  // Crudely limit the use of \p and \P.
  // Otherwise, we will waste time on inputs that have long runs of Unicode
  // character classes. The fuzzer has shown itself to be easily capable of
  // generating such patterns that fall within the other limits, but result
  // in timeouts nonetheless. The marginal cost is high - even more so when
  // counted repetition is involved - whereas the marginal benefit is zero.
  int backslash_p = 0;
  for (size_t i = 0; i < size; i++) {
    if (data[i] == '\\' && i+1 < size && (data[i+1] == 'p' || data[i+1] == 'P'))
      backslash_p++;
  }
  if (backslash_p > 10)
    return 0;

  // The one-at-a-time hash by Bob Jenkins.
  uint32_t hash = 0;
  for (size_t i = 0; i < size; i++) {
    hash += data[i];
    hash += (hash << 10);
    hash ^= (hash >> 6);
  }
  hash += (hash << 3);
  hash ^= (hash >> 11);
  hash += (hash << 15);

  RE2::Options options;
  options.set_log_errors(false);
  options.set_max_mem(64 << 20);
  options.set_encoding(hash & 1 ? RE2::Options::EncodingLatin1
                                : RE2::Options::EncodingUTF8);
  options.set_posix_syntax(hash & 2);
  options.set_longest_match(hash & 4);
  options.set_literal(hash & 8);
  options.set_never_nl(hash & 16);
  options.set_dot_nl(hash & 32);
  options.set_never_capture(hash & 64);
  options.set_case_sensitive(hash & 128);
  options.set_perl_classes(hash & 256);
  options.set_word_boundary(hash & 512);
  options.set_one_line(hash & 1024);

  const char* ptr = reinterpret_cast<const char*>(data);
  int len = static_cast<int>(size);

  StringPiece pattern(ptr, len);
  StringPiece text(ptr, len);
  Test(pattern, options, text);

  return 0;
}
<|endoftext|>


<commit_before>/**
 * \file SharedMemory.cpp
 * \date Mar 18, 2010
 * \author samael
 */

#include <cstring>
#include "SharedMemory.h"
#include "D2MCE.h"

using namespace std;

namespace wfe
{

/**
 * Allocate a piece of shared memory on DSM.
 */
SharedMemory::SharedMemory(string name, size_t size):
		_name(name), _size(size)
{
	d2mce_mutex_init(&_mutex, (name + "_mutex").c_str());
	_buf = (char *)d2mce_malloc(name.c_str(), size);
}

IDrop* SharedMemory::clone() const
{
	SharedMemory *sm = D2MCE::instance()->createSharedMemory(_name, _size);
	memcpy(sm->buffer(), _buf, _size);
	return sm;
}

}
<commit_msg><commit_after>/**
 * \file SharedMemory.cpp
 * \date Mar 18, 2010
 * \author samael
 */

#include <cstring>
#include "SharedMemory.h"
#include "D2MCE.h"

using namespace std;

namespace wfe
{

/**
 * Allocate a piece of shared memory on DSM.
 */
SharedMemory::SharedMemory(string name, size_t size):
		_name(name), _size(size)
{
	d2mce_mutex_init(&_mutex, (name + "_mutex").c_str());
	_buf = (char *)d2mce_malloc(name.c_str(), size);
}

/**
 * Clone the shared memory. It's done by D2MCE::createSharedMemory().
 */
IDrop* SharedMemory::clone() const
{
	SharedMemory *sm = D2MCE::instance()->createSharedMemory(_name, _size);
	memcpy(sm->buffer(), _buf, _size);
	return sm;
}

}
<|endoftext|>


<commit_before>#include "label.h"
#include "../utils/outFile.h"

#include <QDebug>

using namespace utils;

bool Label::init(QDomElement const &element, int index)
{
	mX = QString("%1").arg(static_cast<qreal>(element.attribute("x").toInt()));
	mY = QString("%1").arg(static_cast<qreal>(element.attribute("y").toInt()));
	mText = element.attribute("text");
	mTextBinded = element.attribute("textBinded");
	mReadOnly = element.attribute("readOnly", "false");
	mIndex = index;
	if ((mText == "" && mTextBinded == "") || (mReadOnly != "true" && mReadOnly != "false")) {
		qDebug() << "ERROR: can't parse label";
		return false;
	}
	return true;
}

QString Label::titleName() const
{
	return "title_" + QString("%1").arg(mIndex);
}

void Label::generateCodeForConstructor(OutFile &out)
{
	if (mText.isEmpty()) {
		// Это бинденный лейбл, текст для него будет браться из репозитория
		out() << "			" + titleName() + " = new ElementTitle("
				+ mX + ", " + mY + ", \"" + mTextBinded + "\", " + mReadOnly + ");\n";
	} else {
		// Это статический лейбл, репозиторий ему не нужен
		out() << "			" + titleName() + " = new ElementTitle("
				+ mX + ", " + mY + ", \"" + mText + "\");\n";
	}
	// TODO: вынести отсюда в родительский класс.
	out() << "			" + titleName() + "->setFlags(0);\n"
		<< "			" + titleName() + "->setTextInteractionFlags(Qt::NoTextInteraction);\n"
		<< "			" + titleName() + "->setParentItem(this);\n"
		<< "			mTitles.append(" + titleName() + ");\n";
}

void Label::generateCodeForUpdateData(OutFile &out)
{
	if (mTextBinded.isEmpty())
		return;  // Метка статическая.
	QString field;
	if (mTextBinded == "name")
		field = "mDataIndex.data(Qt::DisplayRole).toString()";
	else
		field = "roleValueByName(\"" + mTextBinded + "\")";  // Кастомное свойство. Если есть желание забиндиться на ещё какое-нибудь из предефайненных, надо тут дописать.

	out() << "			" + titleName() + "->setHtml(QString(\"%1\").arg(" + field + "));\n";
}

void Label::generateCodeForFields(OutFile &out)
{
	out() << "		ElementTitle *" + titleName() + ";\n";
}
<commit_msg>Убраны последствия злоупотребления наркотиками<commit_after>#include "label.h"
#include "../utils/outFile.h"

#include <QDebug>

using namespace utils;

bool Label::init(QDomElement const &element, int index)
{
	mX = element.attribute("x", "0");
	mY = element.attribute("y", "0");
	mText = element.attribute("text");
	mTextBinded = element.attribute("textBinded");
	mReadOnly = element.attribute("readOnly", "false");
	mIndex = index;
	if ((mText == "" && mTextBinded == "") || (mReadOnly != "true" && mReadOnly != "false")) {
		qDebug() << "ERROR: can't parse label";
		return false;
	}
	return true;
}

QString Label::titleName() const
{
	return "title_" + QString("%1").arg(mIndex);
}

void Label::generateCodeForConstructor(OutFile &out)
{
	if (mText.isEmpty()) {
		// Это бинденный лейбл, текст для него будет браться из репозитория
		out() << "			" + titleName() + " = new ElementTitle("
				+ mX + ", " + mY + ", \"" + mTextBinded + "\", " + mReadOnly + ");\n";
	} else {
		// Это статический лейбл, репозиторий ему не нужен
		out() << "			" + titleName() + " = new ElementTitle("
				+ mX + ", " + mY + ", \"" + mText + "\");\n";
	}
	// TODO: вынести отсюда в родительский класс.
	out() << "			" + titleName() + "->setFlags(0);\n"
		<< "			" + titleName() + "->setTextInteractionFlags(Qt::NoTextInteraction);\n"
		<< "			" + titleName() + "->setParentItem(this);\n"
		<< "			mTitles.append(" + titleName() + ");\n";
}

void Label::generateCodeForUpdateData(OutFile &out)
{
	if (mTextBinded.isEmpty())
		return;  // Метка статическая.
	QString field;
	if (mTextBinded == "name")
		field = "mDataIndex.data(Qt::DisplayRole).toString()";
	else
		field = "roleValueByName(\"" + mTextBinded + "\")";  // Кастомное свойство. Если есть желание забиндиться на ещё какое-нибудь из предефайненных, надо тут дописать.

	out() << "			" + titleName() + "->setHtml(QString(\"%1\").arg(" + field + "));\n";
}

void Label::generateCodeForFields(OutFile &out)
{
	out() << "		ElementTitle *" + titleName() + ";\n";
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_HH
#define DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_HH

#include <memory>

#include <dune/stuff/grid/partview.hh>
#include <dune/stuff/grid/provider/interface.hh>

#include "interface.hh"
#include "discontinuouslagrange/fem-localfunctions.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

template< class GridType, Stuff::Grid::ChooseLayer layer_type, ChooseSpaceBackend backend_type,
          int polOrder, class RangeFieldType, int dimRange, int dimRangeCols = 1 >
class DiscontinuousLagrangeProvider
{
  static const Stuff::Grid::ChoosePartView part_view_type = ChooseGridPartView< backend_type >::type;
public:
  typedef typename Stuff::Grid::Layer< GridType, layer_type, part_view_type >::Type GridLayerType;

private:
  template< class G, int p, class R, int r, int rC, GDT::ChooseSpaceBackend b >
  struct SpaceChooser
  {
    static_assert(AlwaysFalse< G >::value, "No space available for this backend!");
  };

  template< class G, int p, class R, int r, int rC >
  struct SpaceChooser< G, p, R, r, rC, GDT::ChooseSpaceBackend::fem_localfunction >
  {
    typedef GDT::Spaces::DiscontinuousLagrange::FemLocalfunctionsBased< GridLayerType, p, R, r > Type;
  };

public:
  typedef typename SpaceChooser< GridType, polOrder, RangeFieldType, dimRange, dimRangeCols, backend_type >::Type Type;

  static Type create(const std::shared_ptr< const GridLayerType > grid_layer)
  {
    return Type(grid_layer);
  }

  static Type create(const Stuff::Grid::ConstProviderInterface< GridType >& grid_provider, const int level = 0)
  {
    return Type(grid_provider.template layer< layer_type, part_view_type >(level));
  }
}; // class DiscontinuousLagrangeProvider

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_HH
<commit_msg>[spaces.discontinuouslagrange] use correct grid provider<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_HH
#define DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_HH

#include <memory>

#if HAVE_DUNE_GRID_MULTISCALE
# include <dune/grid/multiscale/provider/interface.hh>
#endif

#include <dune/stuff/grid/partview.hh>
#include <dune/stuff/grid/provider/interface.hh>

#include "interface.hh"
#include "discontinuouslagrange/fem-localfunctions.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

template< class GridType, Stuff::Grid::ChooseLayer layer_type, ChooseSpaceBackend backend_type,
          int polOrder, class RangeFieldType, int dimRange, int dimRangeCols = 1 >
class DiscontinuousLagrangeProvider
{
  static const Stuff::Grid::ChoosePartView part_view_type = ChooseGridPartView< backend_type >::type;
public:
  typedef typename Stuff::Grid::Layer< GridType, layer_type, part_view_type >::Type GridLayerType;

private:
  template< class G, int p, class R, int r, int rC, GDT::ChooseSpaceBackend b >
  struct SpaceChooser
  {
    static_assert(AlwaysFalse< G >::value, "No space available for this backend!");
  };

  template< class G, int p, class R, int r, int rC >
  struct SpaceChooser< G, p, R, r, rC, GDT::ChooseSpaceBackend::fem_localfunction >
  {
    typedef GDT::Spaces::DiscontinuousLagrange::FemLocalfunctionsBased< GridLayerType, p, R, r > Type;
  };

#if HAVE_DUNE_GRID_MULTISCALE
  typedef grid::Multiscale::ProviderInterface< GridType > GridProviderType;
#else
  typedef Stuff::Grid::ConstProviderInterface< GridType > GridProviderType;
#endif

public:
  typedef typename SpaceChooser< GridType, polOrder, RangeFieldType, dimRange, dimRangeCols, backend_type >::Type Type;

  static Type create(const std::shared_ptr< const GridLayerType > grid_layer)
  {
    return Type(grid_layer);
  }

  static Type create(const GridProviderType& grid_provider, const int level_or_subdomain = 0)
  {
    return Type(grid_provider.template layer< layer_type, part_view_type >(level_or_subdomain));
  }
}; // class DiscontinuousLagrangeProvider

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_DISCONTINUOUSLAGRANGE_HH
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkExhaustiveOptimizer.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkExhaustiveOptimizer.h"
#include "itkCommand.h"
#include "itkEventObject.h"

namespace itk
{

/**
 * Constructor
 */
ExhaustiveOptimizer
::ExhaustiveOptimizer()
{

  itkDebugMacro("Constructor");

  m_StepLength = 1.0;
  m_CurrentIteration   =   0;
  m_CurrentValue = 0;
  m_CurrentIndex.Fill(0);
  m_Stop = false;
  m_NumberOfSteps.Fill(0);
}

/**
 * Start walking
 **/

void ExhaustiveOptimizer::StartOptimization( void )
{
  this->StartWalking();
}

void
ExhaustiveOptimizer
::StartWalking( void )
{

  itkDebugMacro("StartWalking");
  this->InvokeEvent( StartEvent() );

  m_CurrentIteration          = 0;
  m_MaximumNumberOfIterations = 1;

  const unsigned int spaceDimension = this->GetInitialPosition().GetSize();

  for (unsigned int i=0; i< spaceDimension; i++)
    {
    m_MaximumNumberOfIterations *= 2 * m_NumberOfSteps[i];
    }

  m_CurrentIndex.SetSize(spaceDimension);
  m_CurrentIndex.Fill(0);

  this->SetCurrentPosition( this->GetInitialPosition() );

  itkDebugMacro("Calling ResumeWalking");

  this->ResumeWalking();

}

/**
 * Resume the optimization
 */
void
ExhaustiveOptimizer
::ResumeWalking( void )
{
  itkDebugMacro("ResumeWalk");
  m_Stop = false;

  while( !m_Stop )
    {
    ParametersType currentPosition = this->GetCurrentPosition();

    if( m_Stop )
      {
      StopWalking();
      break;
      }

    m_CurrentValue = GetValue( currentPosition );

    if (m_CurrentValue > m_MaximumMetricValue)
      {
      m_MaximumMetricValue = m_CurrentValue;
      m_MaximumMetricValuePosition = currentPosition;
      }
    if (m_CurrentValue < m_MinimumMetricValue)
      {
      m_MinimumMetricValue = m_CurrentValue;
      m_MinimumMetricValuePosition = currentPosition;
      }

    if( m_Stop )
      {
      this->StopWalking();
      break;
      }

    this->AdvanceOneStep();

    m_CurrentIteration++;

    }
}

void
ExhaustiveOptimizer
::StopWalking( void )
{

  itkDebugMacro("StopWalking");

  m_Stop = true;
  this->InvokeEvent( EndEvent() );
}

void
ExhaustiveOptimizer
::AdvanceOneStep( void )
{

  itkDebugMacro("AdvanceOneStep");

  const unsigned int  spaceDimension =
    m_CostFunction->GetNumberOfParameters();

  ScalesType     scales = this->GetScales();

  // Make sure the scales have been set properly
  if (scales.size() != spaceDimension)
    {
    itkExceptionMacro(<< "The size of Scales is "
                      << scales.size()
                      << ", but the NumberOfParameters is "
                      << spaceDimension
                      << ".");
    }

  ParametersType newPosition( spaceDimension );
  ParametersType currentPosition = this->GetCurrentPosition();

  IncrementIndex( newPosition );

  itkDebugMacro(<<"new position = " << newPosition );

  this->InvokeEvent( IterationEvent() );
  this->SetCurrentPosition( newPosition );

}

void
ExhaustiveOptimizer
::IncrementIndex( ParametersType &newPosition )
{

  unsigned int idx = 0;

  const unsigned int  spaceDimension =
    m_CostFunction->GetNumberOfParameters();

  while( idx < spaceDimension )
    {
    m_CurrentIndex[idx]++;

    if( m_CurrentIndex[idx] > (2*m_NumberOfSteps[idx]))
      {
      m_CurrentIndex[idx]=0;
      idx++;
      }
    else
      {
      break;
      }
    }

  if( idx==spaceDimension )
    {
    m_Stop = true;
    }

  for(unsigned int i=0; i<spaceDimension; i++)
    {
    newPosition[i] = (m_CurrentIndex[i]-m_NumberOfSteps[i]) *
                      m_StepLength * this->GetScales()[i] +
                      this->GetInitialPosition()[i];
    }
}

void
ExhaustiveOptimizer
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);

  os << indent << "CurrentValue = " << m_CurrentValue << std::endl;
  os << indent << "NumberOfSteps = " << m_NumberOfSteps << std::endl;
  os << indent << "CurrentIteration = " << m_CurrentIteration << std::endl;
  os << indent << "Stop = " << m_Stop << std::endl;
  os << indent << "CurrentParameter = " << m_CurrentParameter << std::endl;
  os << indent << "StepLength = " << m_StepLength << std::endl;
  os << indent << "CurrentIndex = " << m_CurrentIndex << std::endl;
  os << indent << "MaximumNumberOfIterations = " << m_MaximumNumberOfIterations << std::endl;
  os << indent << "MaximumMetricValue = " << m_MaximumMetricValue << std::endl;
  os << indent << "MinimumMetricValue = " << m_MinimumMetricValue << std::endl;
  os << indent << "MinimumMetricValuePosition = " << m_MinimumMetricValuePosition << std::endl;
  os << indent << "MaximumMetricValuePosition = " << m_MaximumMetricValuePosition << std::endl;
}

} // end namespace itk

<commit_msg>BUG: It was missing to initialize min,max values and positions.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkExhaustiveOptimizer.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkExhaustiveOptimizer.h"
#include "itkCommand.h"
#include "itkEventObject.h"

namespace itk
{

/**
 * Constructor
 */
ExhaustiveOptimizer
::ExhaustiveOptimizer()
{

  itkDebugMacro("Constructor");

  m_StepLength = 1.0;
  m_CurrentIteration   =   0;
  m_CurrentValue = 0;
  m_CurrentIndex.Fill(0);
  m_Stop = false;
  m_NumberOfSteps.Fill(0);
}

/**
 * Start walking
 **/

void ExhaustiveOptimizer::StartOptimization( void )
{
  this->StartWalking();
}

void
ExhaustiveOptimizer
::StartWalking( void )
{

  itkDebugMacro("StartWalking");
  this->InvokeEvent( StartEvent() );

  m_MinimumMetricValuePosition = this->GetInitialPosition();
  m_MaximumMetricValuePosition = this->GetInitialPosition();

  m_MaximumMetricValue = this->GetValue( m_MaximumMetricValuePosition );
  m_MinimumMetricValue = this->GetValue( m_MinimumMetricValuePosition );

  m_CurrentIteration          = 0;
  m_MaximumNumberOfIterations = 1;

  const unsigned int spaceDimension = this->GetInitialPosition().GetSize();

  for (unsigned int i=0; i< spaceDimension; i++)
    {
    m_MaximumNumberOfIterations *= 2 * m_NumberOfSteps[i];
    }

  m_CurrentIndex.SetSize(spaceDimension);
  m_CurrentIndex.Fill(0);

  this->SetCurrentPosition( this->GetInitialPosition() );

  itkDebugMacro("Calling ResumeWalking");

  this->ResumeWalking();

}

/**
 * Resume the optimization
 */
void
ExhaustiveOptimizer
::ResumeWalking( void )
{
  itkDebugMacro("ResumeWalk");
  m_Stop = false;

  while( !m_Stop )
    {
    ParametersType currentPosition = this->GetCurrentPosition();

    if( m_Stop )
      {
      StopWalking();
      break;
      }

    m_CurrentValue = this->GetValue( currentPosition );

    if (m_CurrentValue > m_MaximumMetricValue)
      {
      m_MaximumMetricValue = m_CurrentValue;
      m_MaximumMetricValuePosition = currentPosition;
      }
    if (m_CurrentValue < m_MinimumMetricValue)
      {
      m_MinimumMetricValue = m_CurrentValue;
      m_MinimumMetricValuePosition = currentPosition;
      }

    if( m_Stop )
      {
      this->StopWalking();
      break;
      }

    this->AdvanceOneStep();

    m_CurrentIteration++;

    }
}

void
ExhaustiveOptimizer
::StopWalking( void )
{

  itkDebugMacro("StopWalking");

  m_Stop = true;
  this->InvokeEvent( EndEvent() );
}

void
ExhaustiveOptimizer
::AdvanceOneStep( void )
{

  itkDebugMacro("AdvanceOneStep");

  const unsigned int  spaceDimension =
    m_CostFunction->GetNumberOfParameters();

  ScalesType     scales = this->GetScales();

  // Make sure the scales have been set properly
  if (scales.size() != spaceDimension)
    {
    itkExceptionMacro(<< "The size of Scales is "
                      << scales.size()
                      << ", but the NumberOfParameters is "
                      << spaceDimension
                      << ".");
    }

  ParametersType newPosition( spaceDimension );
  ParametersType currentPosition = this->GetCurrentPosition();

  IncrementIndex( newPosition );

  itkDebugMacro(<<"new position = " << newPosition );

  this->InvokeEvent( IterationEvent() );
  this->SetCurrentPosition( newPosition );

}

void
ExhaustiveOptimizer
::IncrementIndex( ParametersType &newPosition )
{

  unsigned int idx = 0;

  const unsigned int  spaceDimension =
    m_CostFunction->GetNumberOfParameters();

  while( idx < spaceDimension )
    {
    m_CurrentIndex[idx]++;

    if( m_CurrentIndex[idx] > (2*m_NumberOfSteps[idx]))
      {
      m_CurrentIndex[idx]=0;
      idx++;
      }
    else
      {
      break;
      }
    }

  if( idx==spaceDimension )
    {
    m_Stop = true;
    }

  for(unsigned int i=0; i<spaceDimension; i++)
    {
    newPosition[i] = (m_CurrentIndex[i]-m_NumberOfSteps[i]) *
                      m_StepLength * this->GetScales()[i] +
                      this->GetInitialPosition()[i];
    }
}

void
ExhaustiveOptimizer
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);

  os << indent << "CurrentValue = " << m_CurrentValue << std::endl;
  os << indent << "NumberOfSteps = " << m_NumberOfSteps << std::endl;
  os << indent << "CurrentIteration = " << m_CurrentIteration << std::endl;
  os << indent << "Stop = " << m_Stop << std::endl;
  os << indent << "CurrentParameter = " << m_CurrentParameter << std::endl;
  os << indent << "StepLength = " << m_StepLength << std::endl;
  os << indent << "CurrentIndex = " << m_CurrentIndex << std::endl;
  os << indent << "MaximumNumberOfIterations = " << m_MaximumNumberOfIterations << std::endl;
  os << indent << "MaximumMetricValue = " << m_MaximumMetricValue << std::endl;
  os << indent << "MinimumMetricValue = " << m_MinimumMetricValue << std::endl;
  os << indent << "MinimumMetricValuePosition = " << m_MinimumMetricValuePosition << std::endl;
  os << indent << "MaximumMetricValuePosition = " << m_MaximumMetricValuePosition << std::endl;
}

} // end namespace itk

<|endoftext|>