text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/plugin_observer.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/plugin_installer_infobar_delegate.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/simple_alert_infobar_delegate.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/view_messages.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/plugins/npapi/default_plugin_shared.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/npapi/webplugininfo.h"
namespace {
// PluginInfoBarDelegate ------------------------------------------------------
class PluginInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
PluginInfoBarDelegate(TabContents* tab_contents, const string16& name);
protected:
virtual ~PluginInfoBarDelegate();
// ConfirmInfoBarDelegate:
virtual void InfoBarClosed();
virtual bool Cancel();
virtual bool LinkClicked(WindowOpenDisposition disposition);
string16 name_;
TabContents* tab_contents_;
private:
// ConfirmInfoBarDelegate:
virtual SkBitmap* GetIcon() const;
virtual string16 GetLinkText();
DISALLOW_COPY_AND_ASSIGN(PluginInfoBarDelegate);
};
PluginInfoBarDelegate::PluginInfoBarDelegate(TabContents* tab_contents,
const string16& name)
: ConfirmInfoBarDelegate(tab_contents),
name_(name),
tab_contents_(tab_contents) {
}
PluginInfoBarDelegate::~PluginInfoBarDelegate() {
}
void PluginInfoBarDelegate::InfoBarClosed() {
delete this;
}
bool PluginInfoBarDelegate::Cancel() {
tab_contents_->render_view_host()->LoadBlockedPlugins();
return true;
}
bool PluginInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
GURL url = google_util::AppendGoogleLocaleParam(
GURL(chrome::kOutdatedPluginLearnMoreURL));
tab_contents_->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
return false;
}
SkBitmap* PluginInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_INSTALL);
}
string16 PluginInfoBarDelegate::GetLinkText() {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
// BlockedPluginInfoBarDelegate -----------------------------------------------
class BlockedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
BlockedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name);
private:
virtual ~BlockedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
DISALLOW_COPY_AND_ASSIGN(BlockedPluginInfoBarDelegate);
};
BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name)
: PluginInfoBarDelegate(tab_contents, utf16_name) {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer"));
}
BlockedPluginInfoBarDelegate::~BlockedPluginInfoBarDelegate() {
}
string16 BlockedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, name_);
}
string16 BlockedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_ENABLE_ALWAYS : IDS_PLUGIN_ENABLE_TEMPORARILY);
}
bool BlockedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AlwaysAllow"));
tab_contents_->profile()->GetHostContentSettingsMap()->AddExceptionForURL(
tab_contents_->GetURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(),
CONTENT_SETTING_ALLOW);
tab_contents_->render_view_host()->LoadBlockedPlugins();
return true;
}
bool BlockedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AllowThisTime"));
return PluginInfoBarDelegate::Cancel();
}
void BlockedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Dismissed"));
}
void BlockedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool BlockedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
// OutdatedPluginInfoBarDelegate ----------------------------------------------
class OutdatedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
OutdatedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name,
const GURL& update_url);
private:
virtual ~OutdatedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
GURL update_url_;
DISALLOW_COPY_AND_ASSIGN(OutdatedPluginInfoBarDelegate);
};
OutdatedPluginInfoBarDelegate::OutdatedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name,
const GURL& update_url)
: PluginInfoBarDelegate(tab_contents, utf16_name),
update_url_(update_url) {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.RealPlayer"));
else if (name == webkit::npapi::PluginGroup::kSilverlightGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Silverlight"));
else if (name == webkit::npapi::PluginGroup::kAdobeReaderGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Reader"));
}
OutdatedPluginInfoBarDelegate::~OutdatedPluginInfoBarDelegate() {
}
string16 OutdatedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED_PROMPT, name_);
}
string16 OutdatedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_UPDATE : IDS_PLUGIN_ENABLE_TEMPORARILY);
}
bool OutdatedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Update"));
tab_contents_->OpenURL(update_url_, GURL(), NEW_FOREGROUND_TAB,
PageTransition::LINK);
return false;
}
bool OutdatedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.AllowThisTime"));
return PluginInfoBarDelegate::Cancel();
}
void OutdatedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Dismissed"));
}
void OutdatedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool OutdatedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
} // namespace
// PluginObserver -------------------------------------------------------------
PluginObserver::PluginObserver(TabContents* tab_contents)
: TabContentsObserver(tab_contents) {
}
PluginObserver::~PluginObserver() {
}
bool PluginObserver::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(PluginObserver, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_MissingPluginStatus, OnMissingPluginStatus)
IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)
IPC_MESSAGE_HANDLER(ViewHostMsg_BlockedOutdatedPlugin,
OnBlockedOutdatedPlugin)
IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP()
return true;
}
PluginInstallerInfoBarDelegate* PluginObserver::GetPluginInstaller() {
if (plugin_installer_ == NULL)
plugin_installer_.reset(new PluginInstallerInfoBarDelegate(tab_contents()));
return plugin_installer_->AsPluginInstallerInfoBarDelegate();
}
void PluginObserver::OnMissingPluginStatus(int status) {
// TODO(PORT): pull in when plug-ins work
#if defined(OS_WIN)
if (status == webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE) {
tab_contents()->AddInfoBar(
new PluginInstallerInfoBarDelegate(tab_contents()));
return;
}
DCHECK_EQ(webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD,
status);
for (size_t i = 0; i < tab_contents()->infobar_count(); ++i) {
InfoBarDelegate* delegate = tab_contents()->GetInfoBarDelegateAt(i);
if (delegate->AsPluginInstallerInfoBarDelegate() != NULL) {
tab_contents()->RemoveInfoBar(delegate);
return;
}
}
#endif
}
void PluginObserver::OnCrashedPlugin(const FilePath& plugin_path) {
DCHECK(!plugin_path.value().empty());
string16 plugin_name = plugin_path.LossyDisplayName();
webkit::npapi::WebPluginInfo plugin_info;
if (webkit::npapi::PluginList::Singleton()->GetPluginInfoByPath(
plugin_path, &plugin_info) &&
!plugin_info.name.empty()) {
plugin_name = plugin_info.name;
#if defined(OS_MACOSX)
// Many plugins on the Mac have .plugin in the actual name, which looks
// terrible, so look for that and strip it off if present.
const std::string kPluginExtension = ".plugin";
if (EndsWith(plugin_name, ASCIIToUTF16(kPluginExtension), true))
plugin_name.erase(plugin_name.length() - kPluginExtension.length());
#endif // OS_MACOSX
}
SkBitmap* crash_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_CRASHED);
tab_contents()->AddInfoBar(new SimpleAlertInfoBarDelegate(tab_contents(),
crash_icon,
l10n_util::GetStringFUTF16(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
true));
}
void PluginObserver::OnBlockedOutdatedPlugin(const string16& name,
const GURL& update_url) {
tab_contents()->AddInfoBar(update_url.is_empty() ?
static_cast<InfoBarDelegate*>(new BlockedPluginInfoBarDelegate(
tab_contents(), name)) :
new OutdatedPluginInfoBarDelegate(tab_contents(), name, update_url));
}
<commit_msg>Reverse the buttons in the "blocked plug-in" dialog so that "run this time" is encouraged over "run always on this site". The ordering will now be what we prefer on Windows and Mac, but Linux seems to render the buttons in a different order. I'll look in to that, but for now let's align things correctly for the majority of our users.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/plugin_observer.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/plugin_installer_infobar_delegate.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/simple_alert_infobar_delegate.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/view_messages.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/plugins/npapi/default_plugin_shared.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/npapi/webplugininfo.h"
namespace {
// PluginInfoBarDelegate ------------------------------------------------------
class PluginInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
PluginInfoBarDelegate(TabContents* tab_contents, const string16& name);
protected:
virtual ~PluginInfoBarDelegate();
// ConfirmInfoBarDelegate:
virtual void InfoBarClosed();
virtual bool Cancel();
virtual bool LinkClicked(WindowOpenDisposition disposition);
string16 name_;
TabContents* tab_contents_;
private:
// ConfirmInfoBarDelegate:
virtual SkBitmap* GetIcon() const;
virtual string16 GetLinkText();
DISALLOW_COPY_AND_ASSIGN(PluginInfoBarDelegate);
};
PluginInfoBarDelegate::PluginInfoBarDelegate(TabContents* tab_contents,
const string16& name)
: ConfirmInfoBarDelegate(tab_contents),
name_(name),
tab_contents_(tab_contents) {
}
PluginInfoBarDelegate::~PluginInfoBarDelegate() {
}
void PluginInfoBarDelegate::InfoBarClosed() {
delete this;
}
bool PluginInfoBarDelegate::Cancel() {
tab_contents_->render_view_host()->LoadBlockedPlugins();
return true;
}
bool PluginInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
GURL url = google_util::AppendGoogleLocaleParam(
GURL(chrome::kOutdatedPluginLearnMoreURL));
tab_contents_->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
return false;
}
SkBitmap* PluginInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_INSTALL);
}
string16 PluginInfoBarDelegate::GetLinkText() {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
// BlockedPluginInfoBarDelegate -----------------------------------------------
class BlockedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
BlockedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name);
private:
virtual ~BlockedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
DISALLOW_COPY_AND_ASSIGN(BlockedPluginInfoBarDelegate);
};
BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name)
: PluginInfoBarDelegate(tab_contents, utf16_name) {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer"));
}
BlockedPluginInfoBarDelegate::~BlockedPluginInfoBarDelegate() {
}
string16 BlockedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, name_);
}
string16 BlockedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_ENABLE_TEMPORARILY : IDS_PLUGIN_ENABLE_ALWAYS);
}
bool BlockedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AllowThisTime"));
return PluginInfoBarDelegate::Cancel();
}
bool BlockedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AlwaysAllow"));
tab_contents_->profile()->GetHostContentSettingsMap()->AddExceptionForURL(
tab_contents_->GetURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(),
CONTENT_SETTING_ALLOW);
return PluginInfoBarDelegate::Cancel();
}
void BlockedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Dismissed"));
}
void BlockedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool BlockedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
// OutdatedPluginInfoBarDelegate ----------------------------------------------
class OutdatedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
OutdatedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name,
const GURL& update_url);
private:
virtual ~OutdatedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
GURL update_url_;
DISALLOW_COPY_AND_ASSIGN(OutdatedPluginInfoBarDelegate);
};
OutdatedPluginInfoBarDelegate::OutdatedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name,
const GURL& update_url)
: PluginInfoBarDelegate(tab_contents, utf16_name),
update_url_(update_url) {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.RealPlayer"));
else if (name == webkit::npapi::PluginGroup::kSilverlightGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Silverlight"));
else if (name == webkit::npapi::PluginGroup::kAdobeReaderGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Reader"));
}
OutdatedPluginInfoBarDelegate::~OutdatedPluginInfoBarDelegate() {
}
string16 OutdatedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED_PROMPT, name_);
}
string16 OutdatedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_UPDATE : IDS_PLUGIN_ENABLE_TEMPORARILY);
}
bool OutdatedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Update"));
tab_contents_->OpenURL(update_url_, GURL(), NEW_FOREGROUND_TAB,
PageTransition::LINK);
return false;
}
bool OutdatedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.AllowThisTime"));
return PluginInfoBarDelegate::Cancel();
}
void OutdatedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Dismissed"));
}
void OutdatedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool OutdatedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
} // namespace
// PluginObserver -------------------------------------------------------------
PluginObserver::PluginObserver(TabContents* tab_contents)
: TabContentsObserver(tab_contents) {
}
PluginObserver::~PluginObserver() {
}
bool PluginObserver::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(PluginObserver, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_MissingPluginStatus, OnMissingPluginStatus)
IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)
IPC_MESSAGE_HANDLER(ViewHostMsg_BlockedOutdatedPlugin,
OnBlockedOutdatedPlugin)
IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP()
return true;
}
PluginInstallerInfoBarDelegate* PluginObserver::GetPluginInstaller() {
if (plugin_installer_ == NULL)
plugin_installer_.reset(new PluginInstallerInfoBarDelegate(tab_contents()));
return plugin_installer_->AsPluginInstallerInfoBarDelegate();
}
void PluginObserver::OnMissingPluginStatus(int status) {
// TODO(PORT): pull in when plug-ins work
#if defined(OS_WIN)
if (status == webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE) {
tab_contents()->AddInfoBar(
new PluginInstallerInfoBarDelegate(tab_contents()));
return;
}
DCHECK_EQ(webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD,
status);
for (size_t i = 0; i < tab_contents()->infobar_count(); ++i) {
InfoBarDelegate* delegate = tab_contents()->GetInfoBarDelegateAt(i);
if (delegate->AsPluginInstallerInfoBarDelegate() != NULL) {
tab_contents()->RemoveInfoBar(delegate);
return;
}
}
#endif
}
void PluginObserver::OnCrashedPlugin(const FilePath& plugin_path) {
DCHECK(!plugin_path.value().empty());
string16 plugin_name = plugin_path.LossyDisplayName();
webkit::npapi::WebPluginInfo plugin_info;
if (webkit::npapi::PluginList::Singleton()->GetPluginInfoByPath(
plugin_path, &plugin_info) &&
!plugin_info.name.empty()) {
plugin_name = plugin_info.name;
#if defined(OS_MACOSX)
// Many plugins on the Mac have .plugin in the actual name, which looks
// terrible, so look for that and strip it off if present.
const std::string kPluginExtension = ".plugin";
if (EndsWith(plugin_name, ASCIIToUTF16(kPluginExtension), true))
plugin_name.erase(plugin_name.length() - kPluginExtension.length());
#endif // OS_MACOSX
}
SkBitmap* crash_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_CRASHED);
tab_contents()->AddInfoBar(new SimpleAlertInfoBarDelegate(tab_contents(),
crash_icon,
l10n_util::GetStringFUTF16(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
true));
}
void PluginObserver::OnBlockedOutdatedPlugin(const string16& name,
const GURL& update_url) {
tab_contents()->AddInfoBar(update_url.is_empty() ?
static_cast<InfoBarDelegate*>(new BlockedPluginInfoBarDelegate(
tab_contents(), name)) :
new OutdatedPluginInfoBarDelegate(tab_contents(), name, update_url));
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include <pcl/features/shot_lrf.h>
#include <pcl/features/impl/shot_lrf.hpp>
// Instantiations of specific point types
#ifdef PCL_ONLY_CORE_POINT_TYPES
PCL_INSTANTIATE_PRODUCT(SHOTLocalReferenceFrameEstimation, ((pcl::PointXYZ)(pcl::PointXYZI)(pcl::PointXYZRGBA))((pcl::ReferenceFrame)))
#else
PCL_INSTANTIATE_PRODUCT(SHOTLocalReferenceFrameEstimation, (PCL_XYZ_POINT_TYPES)((pcl::ReferenceFrame)))
#endif
<commit_msg>Added XYZRGB to instantation with core types.<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include <pcl/features/shot_lrf.h>
#include <pcl/features/impl/shot_lrf.hpp>
// Instantiations of specific point types
#ifdef PCL_ONLY_CORE_POINT_TYPES
PCL_INSTANTIATE_PRODUCT(SHOTLocalReferenceFrameEstimation, ((pcl::PointXYZ)(pcl::PointXYZI)(pcl::PointXYZRGBA)(pcl::PointXYZRGB))((pcl::ReferenceFrame)))
#else
PCL_INSTANTIATE_PRODUCT(SHOTLocalReferenceFrameEstimation, (PCL_XYZ_POINT_TYPES)((pcl::ReferenceFrame)))
#endif
<|endoftext|>
|
<commit_before>#include "lua_class.h"
#include "../table/table.h"
#include "../util/string_enum.h"
namespace saki
{
bool isValidSuitStr(const std::string &s)
{
return s.size() == 1 && T34::isValidSuit(s[0]);
}
std::string toLower(const char *s)
{
std::string res(s);
std::for_each(res.begin(), res.end(), [](char &c) {
c = static_cast<char>(std::tolower(c));
});
return res;
}
std::pair<Mount::Exit, bool> parseMountExit(const std::string &s)
{
std::pair<Mount::Exit, bool> res;
res.second = true;
if (s == "pii")
res.first = Mount::Exit::PII;
else if (s == "rinshan")
res.first = Mount::Exit::RINSHAN;
else if (s == "dorahyou")
res.first = Mount::Exit::DORAHYOU;
else if (s == "urahyou")
res.first = Mount::Exit::URAHYOU;
else
res.second = false;
return res;
}
template<typename Class, typename Ret, typename... Args>
class AsTable
{
public:
using Method = Ret (Class::*)(Args...) const;
using Table = sol::as_table_t<sol::meta::unqualified_t<Ret>>;
explicit AsTable(Method method)
: mMethod(method)
{
}
Table operator()(Class &thiz, Args... args)
{
return sol::as_table((thiz.*mMethod)(args...));
}
private:
Method mMethod;
};
void setupLuaClasses(const sol::environment &env, LuaUserErrorHandler &error)
{
setupLuaTile(env, error);
setupLuaWho(env);
setupLuaMeld(env, error);
setupLuaExist(env, error);
setupLuaMount(env, error);
setupLuaTileCount(env, error);
setupLuaHand(env);
setupLuaGame(env);
}
void setupLuaTile(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<T34>(
"T34",
sol::meta_function::construct, sol::factories(
[&error](int ti) {
if (ti < 0 || ti >= 34) {
error.handleUserError("invalid T34 id");
return T34();
}
return T34(ti);
},
[&error](const std::string s) {
static const std::array<std::string, 34> dict {
"1m", "2m", "3m", "4m", "5m", "6m", "7m", "8m", "9m",
"1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p",
"1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s",
"1f", "2f", "3f", "4f", "1y", "2y", "3y"
};
auto it = std::find(dict.begin(), dict.end(), s);
if (it == dict.end()) {
error.handleUserError("invalid T34 string");
return T34();
}
return T34(static_cast<int>(it - dict.begin()));
}
),
"id34", &T34::id34,
"suit", [](T34 t) { return T34::charOf(t.suit()); },
"val", &T34::val,
"str34", &T34::str34,
"isz", &T34::isZ,
"isnum", &T34::isNum,
"isnum19", &T34::isNum19,
"isyao", &T34::isYao,
"isyakuhai", &T34::isYakuhai,
"dora", &T34::dora,
"indicator", &T34::indicator,
sol::meta_function::to_string, &T34::str34,
sol::meta_function::equal_to, &T34::operator==,
sol::meta_function::less_than, &T34::operator<,
sol::meta_function::modulus, &T34::operator%,
"all", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end()))
);
env.new_usertype<T37>(
"T37",
sol::meta_function::construct, sol::factories(
[&error](int ti) {
if (ti < 0 || ti >= 34) {
error.handleUserError("invalid T34 id");
return T37();
}
return T37(ti);
},
[&error](const std::string s) {
if (!T37::isValidStr(s.c_str())) {
error.handleUserError("invalid T37 suit");
return T37();
}
return T37(s.c_str());
}
),
"isaka5", &T37::isAka5,
"lookssame", &T37::looksSame,
"str37", &T37::str37,
sol::meta_function::to_string, &T37::str37,
sol::base_classes, sol::bases<T34>()
);
}
void setupLuaWho(sol::environment env)
{
env.new_usertype<Who>(
"Who",
"right", &Who::right,
"cross", &Who::cross,
"left", &Who::left,
"bydice", &Who::byDice,
"byturn", &Who::byTurn,
"looksat", &Who::looksAt,
"turnfrom", &Who::turnFrom,
"index", [](Who w) { return w.index() + 1; },
sol::meta_function::to_string, [](Who w) { return w.index() + 1; },
sol::meta_function::equal_to, &Who::operator==
);
}
void setupLuaMeld(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<M37>(
"M37",
"type", [](const M37 &m) {
return toLower(util::stringOf(m.type()));
},
"has", &M37::has,
sol::meta_function::index, [&error](const M37 &m, int index) {
int zeroIndex = index - 1;
int size = static_cast<int>(m.tiles().size());
if (zeroIndex < 0 || zeroIndex > size) {
error.handleUserError("invalid meld index");
return T37();
}
return m[index];
}
);
}
void setupLuaExist(sol::environment env, LuaUserErrorHandler &error)
{
(void) error;
env.new_usertype<Exist>(
"Exist",
"incmk", sol::overload(
[](Exist &exist, T34 t, int delta) {
exist.incMk(t, delta);
},
[](Exist &exist, const T37 &t, int delta) {
exist.incMk(t, delta);
}
)
);
}
void setupLuaMount(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<Mount>(
"Mount",
"remainpii", &Mount::remainPii,
"remainrinshan", &Mount::remainRinshan,
"remaina", sol::overload(
[](Mount &mount, T34 t) {
mount.remainA(t);
},
[](Mount &mount, const T37 &t) {
mount.remainA(t);
}
),
"getdrids", AsTable(&Mount::getDrids),
"geturids", AsTable(&Mount::getUrids),
"lighta", sol::overload(
[](Mount &mount, T34 t, int mk, bool rin) {
mount.lightA(t, mk, rin);
},
[](Mount &mount, const T37 &t, int mk, bool rin) {
mount.lightA(t, mk, rin);
},
[](Mount &mount, T34 t, int mk) {
mount.lightA(t, mk);
},
[](Mount &mount, const T37 &t, int mk) {
mount.lightA(t, mk);
}
),
"lightb", sol::overload(
[](Mount &mount, T34 t, int mk, bool rin) {
mount.lightB(t, mk, rin);
},
[](Mount &mount, const T37 &t, int mk, bool rin) {
mount.lightB(t, mk, rin);
},
[](Mount &mount, T34 t, int mk) {
mount.lightB(t, mk);
},
[](Mount &mount, const T37 &t, int mk) {
mount.lightB(t, mk);
}
),
"incmk", sol::overload(
[&error](Mount &mount, std::string exit, size_t pos, T34 t, int delta, bool bSpace) {
auto [e, ok] = parseMountExit(exit);
if (!ok) {
error.handleUserError("invalid mount exit");
return;
}
mount.incMk(e, pos, t, delta, bSpace);
},
[&error](Mount &mount, std::string exit, size_t pos, const T37 &t, int delta, bool bSpace) {
auto [e, ok] = parseMountExit(exit);
if (!ok) {
error.handleUserError("invalid mount exit");
return;
}
mount.incMk(e, pos, t, delta, bSpace);
}
),
"loadb", &Mount::loadB
);
}
void setupLuaTileCount(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<TileCount>(
"Tilecount",
"ct", sol::overload(
[](const TileCount &tc, T34 t) {
return tc.ct(t);
},
[](const TileCount &tc, const T37 &t) {
return tc.ct(t);
},
[&error](const TileCount &tc, std::string suit) {
if (!isValidSuitStr(suit)) {
error.handleUserError("invalid suit");
return 0;
}
return tc.ct(T34::suitOf(suit[0]));
}
)
);
}
void setupLuaHand(sol::environment env)
{
env.new_usertype<Hand>(
"Hand",
"closed", &Hand::closed,
"ct", &Hand::ct,
"ctaka5", &Hand::ctAka5,
"ready", &Hand::ready,
"step", &Hand::step,
"step4", &Hand::step4,
"step7", &Hand::step7,
"step7gb", &Hand::step7Gb,
"step13", &Hand::step13,
"effa", AsTable(&Hand::effA),
"effa4", AsTable(&Hand::effA4),
"ismenzen", &Hand::isMenzen,
"barks", AsTable(&Hand::barks),
"canchii", &Hand::canChii,
"canchiiasleft", &Hand::canChiiAsLeft,
"canchiiasmiddle", &Hand::canChiiAsMiddle,
"canchiiasright", &Hand::canChiiAsRight,
"canpon", &Hand::canPon,
"candaiminkan", &Hand::canDaiminkan,
sol::meta_function::modulus, sol::overload(
[](sol::table ids, const Hand &hand) {
int ct = 0;
for (const auto &[key, ref] : ids) {
(void) ref; // conv-to-opt doesn't work somehow
std::optional<T34> id = ids[key];
if (id == std::nullopt) {
std::optional<T37> id37 = ids[key];
id = id37;
}
if (id != std::nullopt)
ct += *id % hand;
}
return ct;
},
[](T34 indic, const Hand &hand) {
return indic % hand;
}
)
);
}
void setupLuaGame(sol::environment env)
{
env.new_usertype<Table>(
"Game",
"gethand", &Table::getHand,
"getround", &Table::getRound,
"getextraround", &Table::getExtraRound,
"getdealer", &Table::getDealer,
"getselfwind", &Table::getSelfWind,
"getroundwind", &Table::getRoundWind,
"getriver", AsTable(&Table::getRiver),
"riichiestablished", &Table::riichiEstablished
);
}
sol::table toLuaTable(sol::environment env, const TableEvent &event)
{
using TE = TableEvent;
sol::table args = env.create();
switch (event.type()) {
case TE::Type::TABLE_STARTED:
args["seed"] = event.as<TE::TableStarted>().seed;
break;
case TE::Type::FIRST_DEALER_CHOSEN:
args["who"] = event.as<TE::FirstDealerChosen>().who;
break;
case TE::Type::ROUND_STARTED: {
const auto &a = event.as<TE::RoundStarted>();
args["round"] = a.round;
args["extraround"] = a.extraRound;
args["dealer"] = a.dealer;
args["alllast"] = a.allLast;
args["deposit"] = a.deposit;
args["seed"] = a.seed;
break;
}
case TE::Type::DICED: {
const auto &a = event.as<TE::Diced>();
args["die1"] = a.die1;
args["die2"] = a.die2;
break;
}
case TE::Type::DRAWN:
args["who"] = event.as<TE::Drawn>().who;
break;
case TE::Type::DISCARDED:
args["spin"] = event.as<TE::Discarded>().spin;
break;
case TE::Type::RIICHI_CALLED:
args["who"] = event.as<TE::RiichiCalled>().who;
break;
case TE::Type::RIICHI_ESTABLISHED:
args["who"] = event.as<TE::RiichiEstablished>().who;
break;
case TE::Type::BARKED: {
const auto &a = event.as<TE::Barked>();
args["who"] = a.who;
args["bark"] = a.bark;
args["spin"] = a.spin;
break;
}
case TE::Type::ROUND_ENDED: {
const auto &a = event.as<TE::RoundEnded>();
args["result"] = util::stringOf(a.result);
args["openers"] = a.openers;
args["gunner"] = a.gunner;
args["forms"] = a.forms;
break;
}
case TE::Type::TABLE_ENDED: {
const auto &a = event.as<TE::TableEnded>();
args["ranks"] = a.ranks;
args["scores"] = a.scores;
break;
}
case TE::Type::POPPED_UP:
args["who"] = event.as<TE::PoppedUp>().who;
break;
default:
break;
}
return env.create_with(
"type", util::stringOf(event.type()),
"args", args
);
}
} // namespace saki
<commit_msg>fix lua mount:remaina() (fix #54)<commit_after>#include "lua_class.h"
#include "../table/table.h"
#include "../util/string_enum.h"
namespace saki
{
bool isValidSuitStr(const std::string &s)
{
return s.size() == 1 && T34::isValidSuit(s[0]);
}
std::string toLower(const char *s)
{
std::string res(s);
std::for_each(res.begin(), res.end(), [](char &c) {
c = static_cast<char>(std::tolower(c));
});
return res;
}
std::pair<Mount::Exit, bool> parseMountExit(const std::string &s)
{
std::pair<Mount::Exit, bool> res;
res.second = true;
if (s == "pii")
res.first = Mount::Exit::PII;
else if (s == "rinshan")
res.first = Mount::Exit::RINSHAN;
else if (s == "dorahyou")
res.first = Mount::Exit::DORAHYOU;
else if (s == "urahyou")
res.first = Mount::Exit::URAHYOU;
else
res.second = false;
return res;
}
template<typename Class, typename Ret, typename... Args>
class AsTable
{
public:
using Method = Ret (Class::*)(Args...) const;
using Table = sol::as_table_t<sol::meta::unqualified_t<Ret>>;
explicit AsTable(Method method)
: mMethod(method)
{
}
Table operator()(Class &thiz, Args... args)
{
return sol::as_table((thiz.*mMethod)(args...));
}
private:
Method mMethod;
};
void setupLuaClasses(const sol::environment &env, LuaUserErrorHandler &error)
{
setupLuaTile(env, error);
setupLuaWho(env);
setupLuaMeld(env, error);
setupLuaExist(env, error);
setupLuaMount(env, error);
setupLuaTileCount(env, error);
setupLuaHand(env);
setupLuaGame(env);
}
void setupLuaTile(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<T34>(
"T34",
sol::meta_function::construct, sol::factories(
[&error](int ti) {
if (ti < 0 || ti >= 34) {
error.handleUserError("invalid T34 id");
return T34();
}
return T34(ti);
},
[&error](const std::string s) {
static const std::array<std::string, 34> dict {
"1m", "2m", "3m", "4m", "5m", "6m", "7m", "8m", "9m",
"1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p",
"1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s",
"1f", "2f", "3f", "4f", "1y", "2y", "3y"
};
auto it = std::find(dict.begin(), dict.end(), s);
if (it == dict.end()) {
error.handleUserError("invalid T34 string");
return T34();
}
return T34(static_cast<int>(it - dict.begin()));
}
),
"id34", &T34::id34,
"suit", [](T34 t) { return T34::charOf(t.suit()); },
"val", &T34::val,
"str34", &T34::str34,
"isz", &T34::isZ,
"isnum", &T34::isNum,
"isnum19", &T34::isNum19,
"isyao", &T34::isYao,
"isyakuhai", &T34::isYakuhai,
"dora", &T34::dora,
"indicator", &T34::indicator,
sol::meta_function::to_string, &T34::str34,
sol::meta_function::equal_to, &T34::operator==,
sol::meta_function::less_than, &T34::operator<,
sol::meta_function::modulus, &T34::operator%,
"all", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end()))
);
env.new_usertype<T37>(
"T37",
sol::meta_function::construct, sol::factories(
[&error](int ti) {
if (ti < 0 || ti >= 34) {
error.handleUserError("invalid T34 id");
return T37();
}
return T37(ti);
},
[&error](const std::string s) {
if (!T37::isValidStr(s.c_str())) {
error.handleUserError("invalid T37 suit");
return T37();
}
return T37(s.c_str());
}
),
"isaka5", &T37::isAka5,
"lookssame", &T37::looksSame,
"str37", &T37::str37,
sol::meta_function::to_string, &T37::str37,
sol::base_classes, sol::bases<T34>()
);
}
void setupLuaWho(sol::environment env)
{
env.new_usertype<Who>(
"Who",
"right", &Who::right,
"cross", &Who::cross,
"left", &Who::left,
"bydice", &Who::byDice,
"byturn", &Who::byTurn,
"looksat", &Who::looksAt,
"turnfrom", &Who::turnFrom,
"index", [](Who w) { return w.index() + 1; },
sol::meta_function::to_string, [](Who w) { return w.index() + 1; },
sol::meta_function::equal_to, &Who::operator==
);
}
void setupLuaMeld(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<M37>(
"M37",
"type", [](const M37 &m) {
return toLower(util::stringOf(m.type()));
},
"has", &M37::has,
sol::meta_function::index, [&error](const M37 &m, int index) {
int zeroIndex = index - 1;
int size = static_cast<int>(m.tiles().size());
if (zeroIndex < 0 || zeroIndex > size) {
error.handleUserError("invalid meld index");
return T37();
}
return m[index];
}
);
}
void setupLuaExist(sol::environment env, LuaUserErrorHandler &error)
{
(void) error;
env.new_usertype<Exist>(
"Exist",
"incmk", sol::overload(
[](Exist &exist, T34 t, int delta) {
exist.incMk(t, delta);
},
[](Exist &exist, const T37 &t, int delta) {
exist.incMk(t, delta);
}
)
);
}
void setupLuaMount(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<Mount>(
"Mount",
"remainpii", &Mount::remainPii,
"remainrinshan", &Mount::remainRinshan,
"remaina", sol::overload(
[](Mount &mount, T34 t) {
return mount.remainA(t);
},
[](Mount &mount, const T37 &t) {
return mount.remainA(t);
}
),
"getdrids", AsTable(&Mount::getDrids),
"geturids", AsTable(&Mount::getUrids),
"lighta", sol::overload(
[](Mount &mount, T34 t, int mk, bool rin) {
mount.lightA(t, mk, rin);
},
[](Mount &mount, const T37 &t, int mk, bool rin) {
mount.lightA(t, mk, rin);
},
[](Mount &mount, T34 t, int mk) {
mount.lightA(t, mk);
},
[](Mount &mount, const T37 &t, int mk) {
mount.lightA(t, mk);
}
),
"lightb", sol::overload(
[](Mount &mount, T34 t, int mk, bool rin) {
mount.lightB(t, mk, rin);
},
[](Mount &mount, const T37 &t, int mk, bool rin) {
mount.lightB(t, mk, rin);
},
[](Mount &mount, T34 t, int mk) {
mount.lightB(t, mk);
},
[](Mount &mount, const T37 &t, int mk) {
mount.lightB(t, mk);
}
),
"incmk", sol::overload(
[&error](Mount &mount, std::string exit, size_t pos, T34 t, int delta, bool bSpace) {
auto [e, ok] = parseMountExit(exit);
if (!ok) {
error.handleUserError("invalid mount exit");
return;
}
mount.incMk(e, pos, t, delta, bSpace);
},
[&error](Mount &mount, std::string exit, size_t pos, const T37 &t, int delta, bool bSpace) {
auto [e, ok] = parseMountExit(exit);
if (!ok) {
error.handleUserError("invalid mount exit");
return;
}
mount.incMk(e, pos, t, delta, bSpace);
}
),
"loadb", &Mount::loadB
);
}
void setupLuaTileCount(sol::environment env, LuaUserErrorHandler &error)
{
env.new_usertype<TileCount>(
"Tilecount",
"ct", sol::overload(
[](const TileCount &tc, T34 t) {
return tc.ct(t);
},
[](const TileCount &tc, const T37 &t) {
return tc.ct(t);
},
[&error](const TileCount &tc, std::string suit) {
if (!isValidSuitStr(suit)) {
error.handleUserError("invalid suit");
return 0;
}
return tc.ct(T34::suitOf(suit[0]));
}
)
);
}
void setupLuaHand(sol::environment env)
{
env.new_usertype<Hand>(
"Hand",
"closed", &Hand::closed,
"ct", &Hand::ct,
"ctaka5", &Hand::ctAka5,
"ready", &Hand::ready,
"step", &Hand::step,
"step4", &Hand::step4,
"step7", &Hand::step7,
"step7gb", &Hand::step7Gb,
"step13", &Hand::step13,
"effa", AsTable(&Hand::effA),
"effa4", AsTable(&Hand::effA4),
"ismenzen", &Hand::isMenzen,
"barks", AsTable(&Hand::barks),
"canchii", &Hand::canChii,
"canchiiasleft", &Hand::canChiiAsLeft,
"canchiiasmiddle", &Hand::canChiiAsMiddle,
"canchiiasright", &Hand::canChiiAsRight,
"canpon", &Hand::canPon,
"candaiminkan", &Hand::canDaiminkan,
sol::meta_function::modulus, sol::overload(
[](sol::table ids, const Hand &hand) {
int ct = 0;
for (const auto &[key, ref] : ids) {
(void) ref; // conv-to-opt doesn't work somehow
std::optional<T34> id = ids[key];
if (id == std::nullopt) {
std::optional<T37> id37 = ids[key];
id = id37;
}
if (id != std::nullopt)
ct += *id % hand;
}
return ct;
},
[](T34 indic, const Hand &hand) {
return indic % hand;
}
)
);
}
void setupLuaGame(sol::environment env)
{
env.new_usertype<Table>(
"Game",
"gethand", &Table::getHand,
"getround", &Table::getRound,
"getextraround", &Table::getExtraRound,
"getdealer", &Table::getDealer,
"getselfwind", &Table::getSelfWind,
"getroundwind", &Table::getRoundWind,
"getriver", AsTable(&Table::getRiver),
"riichiestablished", &Table::riichiEstablished
);
}
sol::table toLuaTable(sol::environment env, const TableEvent &event)
{
using TE = TableEvent;
sol::table args = env.create();
switch (event.type()) {
case TE::Type::TABLE_STARTED:
args["seed"] = event.as<TE::TableStarted>().seed;
break;
case TE::Type::FIRST_DEALER_CHOSEN:
args["who"] = event.as<TE::FirstDealerChosen>().who;
break;
case TE::Type::ROUND_STARTED: {
const auto &a = event.as<TE::RoundStarted>();
args["round"] = a.round;
args["extraround"] = a.extraRound;
args["dealer"] = a.dealer;
args["alllast"] = a.allLast;
args["deposit"] = a.deposit;
args["seed"] = a.seed;
break;
}
case TE::Type::DICED: {
const auto &a = event.as<TE::Diced>();
args["die1"] = a.die1;
args["die2"] = a.die2;
break;
}
case TE::Type::DRAWN:
args["who"] = event.as<TE::Drawn>().who;
break;
case TE::Type::DISCARDED:
args["spin"] = event.as<TE::Discarded>().spin;
break;
case TE::Type::RIICHI_CALLED:
args["who"] = event.as<TE::RiichiCalled>().who;
break;
case TE::Type::RIICHI_ESTABLISHED:
args["who"] = event.as<TE::RiichiEstablished>().who;
break;
case TE::Type::BARKED: {
const auto &a = event.as<TE::Barked>();
args["who"] = a.who;
args["bark"] = a.bark;
args["spin"] = a.spin;
break;
}
case TE::Type::ROUND_ENDED: {
const auto &a = event.as<TE::RoundEnded>();
args["result"] = util::stringOf(a.result);
args["openers"] = a.openers;
args["gunner"] = a.gunner;
args["forms"] = a.forms;
break;
}
case TE::Type::TABLE_ENDED: {
const auto &a = event.as<TE::TableEnded>();
args["ranks"] = a.ranks;
args["scores"] = a.scores;
break;
}
case TE::Type::POPPED_UP:
args["who"] = event.as<TE::PoppedUp>().who;
break;
default:
break;
}
return env.create_with(
"type", util::stringOf(event.type()),
"args", args
);
}
} // namespace saki
<|endoftext|>
|
<commit_before>#include "Iop_Dynamic.h"
using namespace Iop;
CDynamic::CDynamic(uint32* exportTable)
: m_exportTable(exportTable)
, m_name(reinterpret_cast<char*>(m_exportTable) + 12)
{
}
CDynamic::~CDynamic()
{
}
std::string CDynamic::GetId() const
{
return m_name;
}
std::string CDynamic::GetFunctionName(unsigned int functionId) const
{
return "unknown";
}
void CDynamic::Invoke(CMIPS& context, unsigned int functionId)
{
uint32 functionAddress = m_exportTable[5 + functionId];
context.m_State.nGPR[CMIPS::RA].nD0 = context.m_State.nPC;
context.m_State.nPC = functionAddress;
}
uint32* CDynamic::GetExportTable() const
{
return m_exportTable;
}
<commit_msg>In Iop_Dynamic, return "unknown_xxxx" instead of just "unknown" to better distinguish the unknown functions.<commit_after>#include "Iop_Dynamic.h"
using namespace Iop;
CDynamic::CDynamic(uint32* exportTable)
: m_exportTable(exportTable)
, m_name(reinterpret_cast<char*>(m_exportTable) + 12)
{
}
CDynamic::~CDynamic()
{
}
std::string CDynamic::GetId() const
{
return m_name;
}
std::string CDynamic::GetFunctionName(unsigned int functionId) const
{
char functionName[256];
sprintf(functionName, "unknown_%0.4X", functionId);
return functionName;
}
void CDynamic::Invoke(CMIPS& context, unsigned int functionId)
{
uint32 functionAddress = m_exportTable[5 + functionId];
context.m_State.nGPR[CMIPS::RA].nD0 = context.m_State.nPC;
context.m_State.nPC = functionAddress;
}
uint32* CDynamic::GetExportTable() const
{
return m_exportTable;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit 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 "OrbitCaptureClient/CaptureClient.h"
#include <absl/container/flat_hash_set.h>
#include <absl/flags/declare.h>
#include <absl/time/time.h>
#include <cstdint>
#include <outcome.hpp>
#include <string>
#include <type_traits>
#include <utility>
#include "OrbitBase/Future.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/Result.h"
#include "OrbitBase/Tracing.h"
#include "OrbitCaptureClient/CaptureEventProcessor.h"
#include "OrbitCaptureClient/CaptureListener.h"
#include "OrbitClientData/FunctionUtils.h"
#include "OrbitClientData/ModuleData.h"
#include "OrbitClientData/ProcessData.h"
#include "absl/flags/flag.h"
#include "absl/strings/str_format.h"
#include "capture.pb.h"
#include "tracepoint.pb.h"
ABSL_DECLARE_FLAG(uint16_t, sampling_rate);
ABSL_DECLARE_FLAG(bool, frame_pointer_unwinding);
using orbit_client_protos::FunctionInfo;
using orbit_grpc_protos::CaptureOptions;
using orbit_grpc_protos::CaptureRequest;
using orbit_grpc_protos::CaptureResponse;
using orbit_grpc_protos::TracepointInfo;
using orbit_base::Future;
static CaptureOptions::InstrumentedFunction::FunctionType InstrumentedFunctionTypeFromOrbitType(
FunctionInfo::OrbitType orbit_type) {
switch (orbit_type) {
case FunctionInfo::kOrbitTimerStart:
return CaptureOptions::InstrumentedFunction::kTimerStart;
case FunctionInfo::kOrbitTimerStop:
return CaptureOptions::InstrumentedFunction::kTimerStop;
default:
return CaptureOptions::InstrumentedFunction::kRegular;
}
}
Future<ErrorMessageOr<CaptureListener::CaptureOutcome>> CaptureClient::Capture(
ThreadPool* thread_pool, const ProcessData& process,
const orbit_client_data::ModuleManager& module_manager,
absl::flat_hash_map<uint64_t, FunctionInfo> selected_functions,
TracepointInfoSet selected_tracepoints, absl::flat_hash_set<uint64_t> frame_track_function_ids,
bool collect_thread_state, bool enable_introspection,
uint64_t max_local_marker_depth_per_command_buffer) {
absl::MutexLock lock(&state_mutex_);
if (state_ != State::kStopped) {
return {
ErrorMessage("Capture cannot be started, the previous capture is still "
"running/stopping.")};
}
state_ = State::kStarting;
// TODO(168797897) Here a copy of the process is created. The loaded modules of this process were
// likely filled when the process was selected, which might be a while back. Between then and now
// the loaded modules might have changed. Up to date information about which modules are loaded
// should be used here. (Even better: while taking a capture this should always be up to date)
ProcessData process_copy = process;
auto capture_result = thread_pool->Schedule(
[this, process = std::move(process_copy), &module_manager,
selected_functions = std::move(selected_functions), selected_tracepoints,
frame_track_function_ids = std::move(frame_track_function_ids), collect_thread_state,
enable_introspection, max_local_marker_depth_per_command_buffer]() mutable {
return CaptureSync(std::move(process), module_manager, std::move(selected_functions),
std::move(selected_tracepoints), std::move(frame_track_function_ids),
collect_thread_state, enable_introspection,
max_local_marker_depth_per_command_buffer);
});
return capture_result;
}
ErrorMessageOr<CaptureListener::CaptureOutcome> CaptureClient::CaptureSync(
ProcessData&& process, const orbit_client_data::ModuleManager& module_manager,
absl::flat_hash_map<uint64_t, FunctionInfo> selected_functions,
TracepointInfoSet selected_tracepoints, absl::flat_hash_set<uint64_t> frame_track_function_ids,
bool collect_thread_state, bool enable_introspection,
uint64_t max_local_marker_depth_per_command_buffer) {
ORBIT_SCOPE_FUNCTION;
writes_done_failed_ = false;
try_abort_ = false;
{
absl::WriterMutexLock lock{&context_and_stream_mutex_};
CHECK(client_context_ == nullptr);
CHECK(reader_writer_ == nullptr);
client_context_ = std::make_unique<grpc::ClientContext>();
reader_writer_ = capture_service_->Capture(client_context_.get());
}
CaptureRequest request;
CaptureOptions* capture_options = request.mutable_capture_options();
capture_options->set_trace_context_switches(true);
capture_options->set_pid(process.pid());
uint16_t sampling_rate = absl::GetFlag(FLAGS_sampling_rate);
if (sampling_rate == 0) {
capture_options->set_unwinding_method(CaptureOptions::kUndefined);
} else {
capture_options->set_sampling_rate(sampling_rate);
if (absl::GetFlag(FLAGS_frame_pointer_unwinding)) {
capture_options->set_unwinding_method(CaptureOptions::kFramePointers);
} else {
capture_options->set_unwinding_method(CaptureOptions::kDwarf);
}
}
capture_options->set_trace_thread_state(collect_thread_state);
capture_options->set_trace_gpu_driver(true);
capture_options->set_max_local_marker_depth_per_command_buffer(
max_local_marker_depth_per_command_buffer);
for (const auto& [function_id, function] : selected_functions) {
CaptureOptions::InstrumentedFunction* instrumented_function =
capture_options->add_instrumented_functions();
instrumented_function->set_file_path(function.loaded_module_path());
const ModuleData* module = module_manager.GetModuleByPath(function.loaded_module_path());
CHECK(module != nullptr);
instrumented_function->set_file_offset(function_utils::Offset(function, *module));
instrumented_function->set_function_id(function_id);
instrumented_function->set_function_type(
InstrumentedFunctionTypeFromOrbitType(function.orbit_type()));
}
for (const auto& tracepoint : selected_tracepoints) {
TracepointInfo* instrumented_tracepoint = capture_options->add_instrumented_tracepoint();
instrumented_tracepoint->set_category(tracepoint.category());
instrumented_tracepoint->set_name(tracepoint.name());
}
capture_options->set_enable_introspection(enable_introspection);
bool request_write_succeeded;
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
request_write_succeeded = reader_writer_->Write(request);
if (!request_write_succeeded) {
reader_writer_->WritesDone();
}
}
if (!request_write_succeeded) {
ERROR("Sending CaptureRequest on Capture's gRPC stream");
ErrorMessageOr<void> finish_result = FinishCapture();
std::string error_string =
absl::StrFormat("Error sending capture request.%s",
finish_result.has_error() ? ("\n" + finish_result.error().message()) : "");
return ErrorMessage{error_string};
}
LOG("Sent CaptureRequest on Capture's gRPC stream: asking to start capturing");
{
absl::MutexLock lock{&state_mutex_};
state_ = State::kStarted;
}
CaptureEventProcessor event_processor(capture_listener_);
capture_listener_->OnCaptureStarted(std::move(process), std::move(selected_functions),
std::move(selected_tracepoints),
std::move(frame_track_function_ids));
while (!writes_done_failed_ && !try_abort_) {
CaptureResponse response;
bool read_succeeded;
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
read_succeeded = reader_writer_->Read(&response);
}
if (read_succeeded) {
event_processor.ProcessEvents(response.capture_events());
} else {
break;
}
}
ErrorMessageOr<void> finish_result = FinishCapture();
if (try_abort_) {
LOG("TryCancel on Capture's gRPC context was called: Read on Capture's gRPC stream failed");
return CaptureListener::CaptureOutcome::kCancelled;
}
if (writes_done_failed_) {
LOG("WritesDone on Capture's gRPC stream failed: stop reading and try to finish the gRPC call");
std::string error_string = absl::StrFormat(
"Unable to finish the capture in orderly manner, performing emergency stop.%s",
finish_result.has_error() ? ("\n" + finish_result.error().message()) : "");
return ErrorMessage{error_string};
}
LOG("Finished reading from Capture's gRPC stream: all capture data has been received");
if (finish_result.has_error()) {
return ErrorMessage{absl::StrFormat(
"Unable to finish the capture in an orderly manner. The following error occurred: %s",
finish_result.error().message())};
}
return CaptureListener::CaptureOutcome::kComplete;
}
bool CaptureClient::StopCapture() {
{
absl::MutexLock lock(&state_mutex_);
if (state_ == State::kStarting) {
// Block and wait until the state is not kStarting
bool (*is_not_starting)(State*) = [](State* state) { return *state != State::kStarting; };
state_mutex_.Await(absl::Condition(is_not_starting, &state_));
}
if (state_ != State::kStarted) {
LOG("StopCapture ignored, because it is already stopping or stopped");
return false;
}
state_ = State::kStopping;
}
bool writes_done_succeeded;
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
CHECK(reader_writer_ != nullptr);
writes_done_succeeded = reader_writer_->WritesDone();
}
if (!writes_done_succeeded) {
// Normally the capture thread waits until service stops sending messages,
// but in this case since we failed to notify the service we pull emergency
// stop plug. Setting this flag forces capture thread to exit as soon
// as it notices that it was set.
ERROR(
"WritesDone on Capture's gRPC stream failed: unable to finish the "
"capture in orderly manner, initiating emergency stop");
writes_done_failed_ = true;
} else {
LOG("Finished writing on Capture's gRPC stream: asking to stop capturing");
}
return true;
}
bool CaptureClient::AbortCaptureAndWait(int64_t max_wait_ms) {
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
if (client_context_ == nullptr) {
LOG("AbortCaptureAndWait ignored: no ClientContext to TryCancel");
return false;
}
LOG("Calling TryCancel on Capture's gRPC context: aborting the capture");
try_abort_ = true;
client_context_->TryCancel(); // reader_writer_->Read in Capture should then fail
}
// With this wait we want to leave at least some time for FinishCapture to be called, so that
// reader_writer_ and in particular client_context_ are destroyed before returning to the caller.
{
absl::MutexLock lock(&state_mutex_);
state_mutex_.AwaitWithTimeout(
absl::Condition(
+[](State* state) { return *state == State::kStopped; }, &state_),
absl::Milliseconds(max_wait_ms));
}
return true;
}
ErrorMessageOr<void> CaptureClient::FinishCapture() {
ORBIT_SCOPE_FUNCTION;
grpc::Status status;
{
absl::WriterMutexLock lock{&context_and_stream_mutex_};
CHECK(reader_writer_ != nullptr);
status = reader_writer_->Finish();
reader_writer_.reset();
CHECK(client_context_ != nullptr);
client_context_.reset();
}
{
absl::MutexLock lock(&state_mutex_);
state_ = State::kStopped;
}
if (!status.ok()) {
ERROR("Finishing gRPC call to Capture: %s", status.error_message());
return ErrorMessage{status.error_message()};
}
return outcome::success();
}
<commit_msg>Handle Async types in InstrumentedFunctionTypeFromOrbitType<commit_after>// Copyright (c) 2020 The Orbit 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 "OrbitCaptureClient/CaptureClient.h"
#include <absl/container/flat_hash_set.h>
#include <absl/flags/declare.h>
#include <absl/time/time.h>
#include <cstdint>
#include <outcome.hpp>
#include <string>
#include <type_traits>
#include <utility>
#include "OrbitBase/Future.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/Result.h"
#include "OrbitBase/Tracing.h"
#include "OrbitCaptureClient/CaptureEventProcessor.h"
#include "OrbitCaptureClient/CaptureListener.h"
#include "OrbitClientData/FunctionUtils.h"
#include "OrbitClientData/ModuleData.h"
#include "OrbitClientData/ProcessData.h"
#include "absl/flags/flag.h"
#include "absl/strings/str_format.h"
#include "capture.pb.h"
#include "tracepoint.pb.h"
ABSL_DECLARE_FLAG(uint16_t, sampling_rate);
ABSL_DECLARE_FLAG(bool, frame_pointer_unwinding);
using orbit_client_protos::FunctionInfo;
using orbit_grpc_protos::CaptureOptions;
using orbit_grpc_protos::CaptureRequest;
using orbit_grpc_protos::CaptureResponse;
using orbit_grpc_protos::TracepointInfo;
using orbit_base::Future;
static CaptureOptions::InstrumentedFunction::FunctionType InstrumentedFunctionTypeFromOrbitType(
FunctionInfo::OrbitType orbit_type) {
switch (orbit_type) {
case FunctionInfo::kOrbitTimerStart:
case FunctionInfo::kOrbitTimerStartAsync:
return CaptureOptions::InstrumentedFunction::kTimerStart;
case FunctionInfo::kOrbitTimerStop:
case FunctionInfo::kOrbitTimerStopAsync:
return CaptureOptions::InstrumentedFunction::kTimerStop;
case FunctionInfo::kOrbitTrackValue:
case FunctionInfo::kNone:
return CaptureOptions::InstrumentedFunction::kRegular;
case orbit_client_protos::
FunctionInfo_OrbitType_FunctionInfo_OrbitType_INT_MIN_SENTINEL_DO_NOT_USE_:
case orbit_client_protos::
FunctionInfo_OrbitType_FunctionInfo_OrbitType_INT_MAX_SENTINEL_DO_NOT_USE_:
UNREACHABLE();
}
}
Future<ErrorMessageOr<CaptureListener::CaptureOutcome>> CaptureClient::Capture(
ThreadPool* thread_pool, const ProcessData& process,
const orbit_client_data::ModuleManager& module_manager,
absl::flat_hash_map<uint64_t, FunctionInfo> selected_functions,
TracepointInfoSet selected_tracepoints, absl::flat_hash_set<uint64_t> frame_track_function_ids,
bool collect_thread_state, bool enable_introspection,
uint64_t max_local_marker_depth_per_command_buffer) {
absl::MutexLock lock(&state_mutex_);
if (state_ != State::kStopped) {
return {
ErrorMessage("Capture cannot be started, the previous capture is still "
"running/stopping.")};
}
state_ = State::kStarting;
// TODO(168797897) Here a copy of the process is created. The loaded modules of this process were
// likely filled when the process was selected, which might be a while back. Between then and now
// the loaded modules might have changed. Up to date information about which modules are loaded
// should be used here. (Even better: while taking a capture this should always be up to date)
ProcessData process_copy = process;
auto capture_result = thread_pool->Schedule(
[this, process = std::move(process_copy), &module_manager,
selected_functions = std::move(selected_functions), selected_tracepoints,
frame_track_function_ids = std::move(frame_track_function_ids), collect_thread_state,
enable_introspection, max_local_marker_depth_per_command_buffer]() mutable {
return CaptureSync(std::move(process), module_manager, std::move(selected_functions),
std::move(selected_tracepoints), std::move(frame_track_function_ids),
collect_thread_state, enable_introspection,
max_local_marker_depth_per_command_buffer);
});
return capture_result;
}
ErrorMessageOr<CaptureListener::CaptureOutcome> CaptureClient::CaptureSync(
ProcessData&& process, const orbit_client_data::ModuleManager& module_manager,
absl::flat_hash_map<uint64_t, FunctionInfo> selected_functions,
TracepointInfoSet selected_tracepoints, absl::flat_hash_set<uint64_t> frame_track_function_ids,
bool collect_thread_state, bool enable_introspection,
uint64_t max_local_marker_depth_per_command_buffer) {
ORBIT_SCOPE_FUNCTION;
writes_done_failed_ = false;
try_abort_ = false;
{
absl::WriterMutexLock lock{&context_and_stream_mutex_};
CHECK(client_context_ == nullptr);
CHECK(reader_writer_ == nullptr);
client_context_ = std::make_unique<grpc::ClientContext>();
reader_writer_ = capture_service_->Capture(client_context_.get());
}
CaptureRequest request;
CaptureOptions* capture_options = request.mutable_capture_options();
capture_options->set_trace_context_switches(true);
capture_options->set_pid(process.pid());
uint16_t sampling_rate = absl::GetFlag(FLAGS_sampling_rate);
if (sampling_rate == 0) {
capture_options->set_unwinding_method(CaptureOptions::kUndefined);
} else {
capture_options->set_sampling_rate(sampling_rate);
if (absl::GetFlag(FLAGS_frame_pointer_unwinding)) {
capture_options->set_unwinding_method(CaptureOptions::kFramePointers);
} else {
capture_options->set_unwinding_method(CaptureOptions::kDwarf);
}
}
capture_options->set_trace_thread_state(collect_thread_state);
capture_options->set_trace_gpu_driver(true);
capture_options->set_max_local_marker_depth_per_command_buffer(
max_local_marker_depth_per_command_buffer);
for (const auto& [function_id, function] : selected_functions) {
CaptureOptions::InstrumentedFunction* instrumented_function =
capture_options->add_instrumented_functions();
instrumented_function->set_file_path(function.loaded_module_path());
const ModuleData* module = module_manager.GetModuleByPath(function.loaded_module_path());
CHECK(module != nullptr);
instrumented_function->set_file_offset(function_utils::Offset(function, *module));
instrumented_function->set_function_id(function_id);
instrumented_function->set_function_type(
InstrumentedFunctionTypeFromOrbitType(function.orbit_type()));
}
for (const auto& tracepoint : selected_tracepoints) {
TracepointInfo* instrumented_tracepoint = capture_options->add_instrumented_tracepoint();
instrumented_tracepoint->set_category(tracepoint.category());
instrumented_tracepoint->set_name(tracepoint.name());
}
capture_options->set_enable_introspection(enable_introspection);
bool request_write_succeeded;
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
request_write_succeeded = reader_writer_->Write(request);
if (!request_write_succeeded) {
reader_writer_->WritesDone();
}
}
if (!request_write_succeeded) {
ERROR("Sending CaptureRequest on Capture's gRPC stream");
ErrorMessageOr<void> finish_result = FinishCapture();
std::string error_string =
absl::StrFormat("Error sending capture request.%s",
finish_result.has_error() ? ("\n" + finish_result.error().message()) : "");
return ErrorMessage{error_string};
}
LOG("Sent CaptureRequest on Capture's gRPC stream: asking to start capturing");
{
absl::MutexLock lock{&state_mutex_};
state_ = State::kStarted;
}
CaptureEventProcessor event_processor(capture_listener_);
capture_listener_->OnCaptureStarted(std::move(process), std::move(selected_functions),
std::move(selected_tracepoints),
std::move(frame_track_function_ids));
while (!writes_done_failed_ && !try_abort_) {
CaptureResponse response;
bool read_succeeded;
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
read_succeeded = reader_writer_->Read(&response);
}
if (read_succeeded) {
event_processor.ProcessEvents(response.capture_events());
} else {
break;
}
}
ErrorMessageOr<void> finish_result = FinishCapture();
if (try_abort_) {
LOG("TryCancel on Capture's gRPC context was called: Read on Capture's gRPC stream failed");
return CaptureListener::CaptureOutcome::kCancelled;
}
if (writes_done_failed_) {
LOG("WritesDone on Capture's gRPC stream failed: stop reading and try to finish the gRPC call");
std::string error_string = absl::StrFormat(
"Unable to finish the capture in orderly manner, performing emergency stop.%s",
finish_result.has_error() ? ("\n" + finish_result.error().message()) : "");
return ErrorMessage{error_string};
}
LOG("Finished reading from Capture's gRPC stream: all capture data has been received");
if (finish_result.has_error()) {
return ErrorMessage{absl::StrFormat(
"Unable to finish the capture in an orderly manner. The following error occurred: %s",
finish_result.error().message())};
}
return CaptureListener::CaptureOutcome::kComplete;
}
bool CaptureClient::StopCapture() {
{
absl::MutexLock lock(&state_mutex_);
if (state_ == State::kStarting) {
// Block and wait until the state is not kStarting
bool (*is_not_starting)(State*) = [](State* state) { return *state != State::kStarting; };
state_mutex_.Await(absl::Condition(is_not_starting, &state_));
}
if (state_ != State::kStarted) {
LOG("StopCapture ignored, because it is already stopping or stopped");
return false;
}
state_ = State::kStopping;
}
bool writes_done_succeeded;
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
CHECK(reader_writer_ != nullptr);
writes_done_succeeded = reader_writer_->WritesDone();
}
if (!writes_done_succeeded) {
// Normally the capture thread waits until service stops sending messages,
// but in this case since we failed to notify the service we pull emergency
// stop plug. Setting this flag forces capture thread to exit as soon
// as it notices that it was set.
ERROR(
"WritesDone on Capture's gRPC stream failed: unable to finish the "
"capture in orderly manner, initiating emergency stop");
writes_done_failed_ = true;
} else {
LOG("Finished writing on Capture's gRPC stream: asking to stop capturing");
}
return true;
}
bool CaptureClient::AbortCaptureAndWait(int64_t max_wait_ms) {
{
absl::ReaderMutexLock lock{&context_and_stream_mutex_};
if (client_context_ == nullptr) {
LOG("AbortCaptureAndWait ignored: no ClientContext to TryCancel");
return false;
}
LOG("Calling TryCancel on Capture's gRPC context: aborting the capture");
try_abort_ = true;
client_context_->TryCancel(); // reader_writer_->Read in Capture should then fail
}
// With this wait we want to leave at least some time for FinishCapture to be called, so that
// reader_writer_ and in particular client_context_ are destroyed before returning to the caller.
{
absl::MutexLock lock(&state_mutex_);
state_mutex_.AwaitWithTimeout(
absl::Condition(
+[](State* state) { return *state == State::kStopped; }, &state_),
absl::Milliseconds(max_wait_ms));
}
return true;
}
ErrorMessageOr<void> CaptureClient::FinishCapture() {
ORBIT_SCOPE_FUNCTION;
grpc::Status status;
{
absl::WriterMutexLock lock{&context_and_stream_mutex_};
CHECK(reader_writer_ != nullptr);
status = reader_writer_->Finish();
reader_writer_.reset();
CHECK(client_context_ != nullptr);
client_context_.reset();
}
{
absl::MutexLock lock(&state_mutex_);
state_ = State::kStopped;
}
if (!status.ok()) {
ERROR("Finishing gRPC call to Capture: %s", status.error_message());
return ErrorMessage{status.error_message()};
}
return outcome::success();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingMinMaxVectorImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"
namespace otb
{
namespace Wrapper
{
class Rescale : public Application
{
public:
/** Standard class typedefs. */
typedef Rescale Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Rescale, otb::Application);
/** Filters typedef */
typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;
typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;
private:
Rescale()
{
SetName("Rescale");
SetDescription("Rescale the image between two given values.");
}
virtual ~Rescale()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
AddParameter(ParameterType_Float, "outmin", "Output min value");
AddParameter(ParameterType_Float, "outmax", "Output max value");
SetParameterFloat("outmin", 0);
SetParameterDescription( "outmin", "Minimum value of the output image." );
SetParameterFloat("outmax", 255);
SetParameterDescription( "outmax", "Maximum value of the output image." );
MandatoryOff("outmin");
MandatoryOff("outmax");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute()
{
FloatVectorImageType::Pointer inImage = GetParameterImage("in");
otbAppLogDEBUG( << "Starting Min/Max computation" )
m_MinMaxFilter = MinMaxFilterType::New();
m_MinMaxFilter->SetInput( inImage );
m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming( 50 );
AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing");
m_MinMaxFilter->Update();
otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum()
<< " max=" << m_MinMaxFilter->GetMaximum() )
FloatVectorImageType::PixelType inMin, inMax;
m_RescaleFilter = RescaleImageFilterType::New();
m_RescaleFilter->SetInput( inImage );
m_RescaleFilter->SetInputMinimum( m_MinMaxFilter->GetMinimum() );
m_RescaleFilter->SetInputMaximum( m_MinMaxFilter->GetMaximum() );
FloatVectorImageType::PixelType outMin, outMax;
outMin.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMax.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMin.Fill( GetParameterFloat("outmin") );
outMax.Fill( GetParameterFloat("outmax") );
m_RescaleFilter->SetOutputMinimum( outMin );
m_RescaleFilter->SetOutputMaximum( outMax );
m_RescaleFilter->UpdateOutputInformation();
SetParameterOutputImage("out", m_RescaleFilter->GetOutput());
}
RescaleImageFilterType::Pointer m_RescaleFilter;
MinMaxFilterType::Pointer m_MinMaxFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::Rescale)
<commit_msg>DOC: Rescale application doc update.<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingMinMaxVectorImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"
namespace otb
{
namespace Wrapper
{
class Rescale : public Application
{
public:
/** Standard class typedefs. */
typedef Rescale Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Rescale, otb::Application);
/** Filters typedef */
typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;
typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;
private:
Rescale()
{
SetName("Rescale");
SetDescription("Rescale the image between two given values.");
SetDocName("Rescale Image Application");
SetDocLongDescription("This application scale the given image pixel intensity between two given values. "
"By default min (resp. max) value is set to 0 (resp. 255).");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
SetDocCLExample("otbApplicationLauncherCommandLine Rescale ${OTB-BIN}/bin"
" --in ${OTB-DATA}/Input/poupees.tif --out rescaledImage.tif --outmin 20 --outmax 150");
AddDocTag("Image Manipulation");
}
virtual ~Rescale()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription( "in", "The image to scale." );
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription( "out" , "The rescaled image filename." );
AddParameter(ParameterType_Float, "outmin", "Output min value");
AddParameter(ParameterType_Float, "outmax", "Output max value");
SetParameterFloat("outmin", 0.0);
SetParameterDescription( "outmin", "Minimum value of the output image." );
SetParameterFloat("outmax", 255.0);
SetParameterDescription( "outmax", "Maximum value of the output image." );
MandatoryOff("outmin");
MandatoryOff("outmax");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute()
{
FloatVectorImageType::Pointer inImage = GetParameterImage("in");
otbAppLogDEBUG( << "Starting Min/Max computation" )
m_MinMaxFilter = MinMaxFilterType::New();
m_MinMaxFilter->SetInput( inImage );
m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming( 50 );
AddProcess(m_MinMaxFilter->GetStreamer(), "Min/Max computing");
m_MinMaxFilter->Update();
otbAppLogDEBUG( << "Min/Max computation done : min=" << m_MinMaxFilter->GetMinimum()
<< " max=" << m_MinMaxFilter->GetMaximum() )
FloatVectorImageType::PixelType inMin, inMax;
m_RescaleFilter = RescaleImageFilterType::New();
m_RescaleFilter->SetInput( inImage );
m_RescaleFilter->SetInputMinimum( m_MinMaxFilter->GetMinimum() );
m_RescaleFilter->SetInputMaximum( m_MinMaxFilter->GetMaximum() );
FloatVectorImageType::PixelType outMin, outMax;
outMin.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMax.SetSize( inImage->GetNumberOfComponentsPerPixel() );
outMin.Fill( GetParameterFloat("outmin") );
outMax.Fill( GetParameterFloat("outmax") );
m_RescaleFilter->SetOutputMinimum( outMin );
m_RescaleFilter->SetOutputMaximum( outMax );
m_RescaleFilter->UpdateOutputInformation();
SetParameterOutputImage("out", m_RescaleFilter->GetOutput());
}
RescaleImageFilterType::Pointer m_RescaleFilter;
MinMaxFilterType::Pointer m_MinMaxFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::Rescale)
<|endoftext|>
|
<commit_before>#include "BoundingBox.hpp"
#include "Exceptions.hpp"
#include "clipper/clipper.hpp"
#include "builders/BuilderContext.hpp"
#include "builders/terrain/LineGridSplitter.hpp"
#include "builders/terrain/TerraBuilder.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "entities/ElementVisitor.hpp"
#include "meshing/Polygon.hpp"
#include "meshing/MeshBuilder.hpp"
#include "utils/CompatibilityUtils.hpp"
#include "utils/GeoUtils.hpp"
#include "utils/MapCssUtils.hpp"
#include "utils/NoiseUtils.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <iterator>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;
const double Scale = 1E7; // max precision for Lat/Lon: seven decimal positions
const double AreaTolerance = 1000; // Tolerance for meshing
// Represents terrain region points.
struct Region
{
bool isLayer;
std::shared_ptr<MeshBuilder::Options> options; // optional: might be empty if polygon is layer
Paths points;
};
typedef std::vector<Point> Points;
typedef std::vector<Region> Regions;
typedef std::unordered_map<std::string, Regions> Layers;
// mapcss specific keys
const static std::string TerrainLayerKey = "terrain-layer";
const static std::string ColorNoiseFreqKey = "color-noise-freq";
const static std::string EleNoiseFreqKey = "ele-noise-freq";
const static std::string GradientKey= "color";
const static std::string MaxAreaKey = "max-area";
const static std::string WidthKey = "width";
const static std::string HeightKey = "height";
const static std::string LayerPriorityKey = "layer-priority";
const static std::string MeshNameKey = "mesh-name";
const static std::string GridCellSize = "grid-cell-size";
class TerraBuilder::TerraBuilderImpl : public ElementBuilder
{
public:
TerraBuilderImpl(const BuilderContext& context) :
ElementBuilder(context),
style_(context.styleProvider.forCanvas(context.quadKey.levelOfDetail)),
splitter_(),
bbox_(GeoUtils::quadKeyToBoundingBox(context_.quadKey)),
rect_(bbox_.minPoint.longitude, bbox_.minPoint.latitude, bbox_.maxPoint.longitude, bbox_.maxPoint.latitude),
mesh_("terrain")
{
tileRect_.push_back(IntPoint(bbox_.minPoint.longitude*Scale, bbox_.minPoint.latitude *Scale));
tileRect_.push_back(IntPoint(bbox_.maxPoint.longitude *Scale, bbox_.minPoint.latitude *Scale));
tileRect_.push_back(IntPoint(bbox_.maxPoint.longitude *Scale, bbox_.maxPoint.latitude*Scale));
tileRect_.push_back(IntPoint(bbox_.minPoint.longitude*Scale, bbox_.maxPoint.latitude*Scale));
clipper_.AddPath(tileRect_, ptClip, true);
double size = utymap::utils::getDimension(GridCellSize, context_.stringTable, style_,
bbox_.maxPoint.latitude - bbox_.minPoint.latitude, bbox_.center());
splitter_.setParams(Scale, size);
}
void visitNode(const utymap::entities::Node& node)
{
}
void visitWay(const utymap::entities::Way& way)
{
Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);
Region region = createRegion(style, way.coordinates);
// make polygon from line by offsetting it using width specified
double width = utymap::utils::getDimension(WidthKey, context_.stringTable, style,
bbox_.maxPoint.latitude - bbox_.minPoint.latitude, bbox_.center());
Paths solution;
offset_.AddPaths(region.points, jtMiter, etOpenSquare);
offset_.Execute(solution, width * Scale);
offset_.Clear();
clipper_.AddPaths(solution, ptSubject, true);
clipper_.Execute(ctIntersection, solution);
clipper_.removeSubject();
region.points = solution;
std::string type = region.isLayer
? *utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
void visitArea(const utymap::entities::Area& area)
{
Style style = context_.styleProvider.forElement(area, context_.quadKey.levelOfDetail);
Region region = createRegion(style, area.coordinates);
std::string type = region.isLayer
? *utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
void visitRelation(const utymap::entities::Relation& relation)
{
Region region;
struct RelationVisitor : public ElementVisitor
{
const Relation& relation;
TerraBuilder::TerraBuilderImpl& builder;
Region& region;
RelationVisitor(TerraBuilder::TerraBuilderImpl& builder, const Relation& relation, Region& region) :
builder(builder), relation(relation), region(region) {}
void visitNode(const utymap::entities::Node& n) { n.accept(builder); }
void visitWay(const utymap::entities::Way& w) { w.accept(builder); }
void visitArea(const utymap::entities::Area& a)
{
Path path;
path.reserve(a.coordinates.size());
for (const GeoCoordinate& c : a.coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
}
void visitRelation(const utymap::entities::Relation& r) { r.accept(builder); }
} visitor(*this, relation, region);
for (const auto& element : relation.elements) {
// if there are no tags, then this element is result of clipping
if (element->tags.empty())
element->tags = relation.tags;
element->accept(visitor);
}
if (!region.points.empty()) {
Style style = context_.styleProvider.forElement(relation, context_.quadKey.levelOfDetail);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
std::string type = region.isLayer
? *utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
}
// builds tile mesh using data provided.
void complete()
{
clipper_.Clear();
buildLayers();
buildBackground();
context_.meshCallback(mesh_);
}
private:
// process all found layers.
void buildLayers()
{
// 1. process layers: regions with shared properties.
std::stringstream ss(*utymap::utils::getString(LayerPriorityKey, context_.stringTable, style_));
while (ss.good()) {
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
buildFromRegions(layer->second, createMeshOptions(style_, name + "-"));
layers_.erase(layer);
}
}
// 2. Process the rest: each region has aready its own properties.
for (auto& layer : layers_)
for (auto& region : layer.second) {
buildFromPaths(region.points, region.options);
}
}
// process the rest area.
void buildBackground()
{
clipper_.AddPath(tileRect_, ptSubject, true);
Paths background;
clipper_.Execute(ctDifference, background, pftPositive, pftPositive);
clipper_.Clear();
if (!background.empty())
populateMesh(createMeshOptions(style_, ""), background);
}
Region createRegion(const Style& style, const std::vector<GeoCoordinate>& coordinates)
{
Region region;
Path path;
path.reserve(coordinates.size());
for (const GeoCoordinate& c : coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
return std::move(region);
}
std::shared_ptr<MeshBuilder::Options> createMeshOptions(const Style& style, const std::string& prefix)
{
double quadKeyWidth = bbox_.maxPoint.latitude - bbox_.minPoint.latitude;
auto gradientKey = utymap::utils::getString(prefix + GradientKey, context_.stringTable, style);
return std::shared_ptr<MeshBuilder::Options>(new MeshBuilder::Options(
utymap::utils::getDimension(prefix + MaxAreaKey, context_.stringTable, style, quadKeyWidth * quadKeyWidth),
utymap::utils::getDouble(prefix + EleNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + ColorNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDimension(prefix + HeightKey, context_.stringTable, style, quadKeyWidth, 0),
context_.styleProvider.getGradient(*gradientKey),
std::numeric_limits<double>::lowest(),
*utymap::utils::getString(prefix + MeshNameKey, context_.stringTable, style, ""),
/* no new vertices on boundaries */ 1));
}
void buildFromRegions(const Regions& regions, const std::shared_ptr<MeshBuilder::Options>& options)
{
// merge all regions together
Clipper clipper;
for (const Region& region : regions)
clipper.AddPaths(region.points, ptSubject, true);
Paths result;
clipper.Execute(ctUnion, result, pftPositive, pftPositive);
buildFromPaths(result, options);
}
void buildFromPaths(Paths& paths, const std::shared_ptr<MeshBuilder::Options>& options)
{
clipper_.AddPaths(paths, ptSubject, true);
paths.clear();
clipper_.Execute(ctDifference, paths, pftPositive, pftPositive);
clipper_.moveSubjectToClip();
populateMesh(options, paths);
}
void populateMesh(const std::shared_ptr<MeshBuilder::Options>& options, Paths& paths)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = std::abs(options->heightOffset) > 1E-8;
// calculate approximate size of overall points
auto size = 0;
for (auto i = 0; i < paths.size(); ++i)
size += paths[i].size() * 1.5;
Polygon polygon(size);
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
bool isHole = area < 0;
if (std::abs(area) < AreaTolerance)
continue;
Points points = restorePoints(path);
if (isHole)
polygon.addHole(points);
else
polygon.addContour(points);
if (hasHeightOffset)
processHeightOffset(options, points, isHole);
}
if (!polygon.points.empty())
fillMesh(options, polygon);
}
// restores mesh points from clipper points and injects new ones according to grid.
Points restorePoints(const Path& path)
{
int lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++)
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
return std::move(points);
}
void fillMesh(const std::shared_ptr<MeshBuilder::Options>& options, Polygon& polygon)
{
if (options->meshName != "") {
Mesh polygonMesh(options->meshName);
context_.meshBuilder.addPolygon(polygonMesh, polygon, *options);
context_.meshCallback(polygonMesh);
}
else {
context_.meshBuilder.addPolygon(mesh_, polygon, *options);
}
}
void processHeightOffset(const std::shared_ptr<MeshBuilder::Options>& options, const Points& points, bool isHole)
{
auto index = mesh_.vertices.size() / 3;
for (auto i = 0; i < points.size(); ++i) {
Point p1 = points[i];
Point p2 = points[i == (points.size() - 1) ? 0 : i + 1];
// check whether two points are on cell rect
if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2)) continue;
context_.meshBuilder.addPlane(mesh_, p1, p2, *options);
}
}
const Style style_;
ClipperEx clipper_;
ClipperOffset offset_;
LineGridSplitter splitter_;
BoundingBox bbox_;
Rectangle rect_;
Path tileRect_;
Layers layers_;
Mesh mesh_;
};
void TerraBuilder::visitNode(const utymap::entities::Node& node) { pimpl_->visitNode(node); }
void TerraBuilder::visitWay(const utymap::entities::Way& way) { pimpl_->visitWay(way); }
void TerraBuilder::visitArea(const utymap::entities::Area& area) { pimpl_->visitArea(area); }
void TerraBuilder::visitRelation(const utymap::entities::Relation& relation) { pimpl_->visitRelation(relation); }
void TerraBuilder::complete() { pimpl_->complete(); }
TerraBuilder::~TerraBuilder() { }
TerraBuilder::TerraBuilder(const BuilderContext& context) :
utymap::builders::ElementBuilder(context),
pimpl_(new TerraBuilder::TerraBuilderImpl(context))
{
}
<commit_msg>core: do not apply elevation noise to height offset polygons<commit_after>#include "BoundingBox.hpp"
#include "Exceptions.hpp"
#include "clipper/clipper.hpp"
#include "builders/BuilderContext.hpp"
#include "builders/terrain/LineGridSplitter.hpp"
#include "builders/terrain/TerraBuilder.hpp"
#include "entities/Node.hpp"
#include "entities/Way.hpp"
#include "entities/Area.hpp"
#include "entities/Relation.hpp"
#include "entities/ElementVisitor.hpp"
#include "meshing/Polygon.hpp"
#include "meshing/MeshBuilder.hpp"
#include "utils/CompatibilityUtils.hpp"
#include "utils/GeoUtils.hpp"
#include "utils/MapCssUtils.hpp"
#include "utils/NoiseUtils.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <iterator>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;
const double Scale = 1E7; // max precision for Lat/Lon: seven decimal positions
const double AreaTolerance = 1000; // Tolerance for meshing
// Represents terrain region points.
struct Region
{
bool isLayer;
std::shared_ptr<MeshBuilder::Options> options; // optional: might be empty if polygon is layer
Paths points;
};
typedef std::vector<Point> Points;
typedef std::vector<Region> Regions;
typedef std::unordered_map<std::string, Regions> Layers;
// mapcss specific keys
const static std::string TerrainLayerKey = "terrain-layer";
const static std::string ColorNoiseFreqKey = "color-noise-freq";
const static std::string EleNoiseFreqKey = "ele-noise-freq";
const static std::string GradientKey= "color";
const static std::string MaxAreaKey = "max-area";
const static std::string WidthKey = "width";
const static std::string HeightKey = "height";
const static std::string LayerPriorityKey = "layer-priority";
const static std::string MeshNameKey = "mesh-name";
const static std::string GridCellSize = "grid-cell-size";
class TerraBuilder::TerraBuilderImpl : public ElementBuilder
{
public:
TerraBuilderImpl(const BuilderContext& context) :
ElementBuilder(context),
style_(context.styleProvider.forCanvas(context.quadKey.levelOfDetail)),
splitter_(),
bbox_(GeoUtils::quadKeyToBoundingBox(context_.quadKey)),
rect_(bbox_.minPoint.longitude, bbox_.minPoint.latitude, bbox_.maxPoint.longitude, bbox_.maxPoint.latitude),
mesh_("terrain")
{
tileRect_.push_back(IntPoint(bbox_.minPoint.longitude*Scale, bbox_.minPoint.latitude *Scale));
tileRect_.push_back(IntPoint(bbox_.maxPoint.longitude *Scale, bbox_.minPoint.latitude *Scale));
tileRect_.push_back(IntPoint(bbox_.maxPoint.longitude *Scale, bbox_.maxPoint.latitude*Scale));
tileRect_.push_back(IntPoint(bbox_.minPoint.longitude*Scale, bbox_.maxPoint.latitude*Scale));
clipper_.AddPath(tileRect_, ptClip, true);
double size = utymap::utils::getDimension(GridCellSize, context_.stringTable, style_,
bbox_.maxPoint.latitude - bbox_.minPoint.latitude, bbox_.center());
splitter_.setParams(Scale, size);
}
void visitNode(const utymap::entities::Node& node)
{
}
void visitWay(const utymap::entities::Way& way)
{
Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);
Region region = createRegion(style, way.coordinates);
// make polygon from line by offsetting it using width specified
double width = utymap::utils::getDimension(WidthKey, context_.stringTable, style,
bbox_.maxPoint.latitude - bbox_.minPoint.latitude, bbox_.center());
Paths solution;
offset_.AddPaths(region.points, jtMiter, etOpenSquare);
offset_.Execute(solution, width * Scale);
offset_.Clear();
clipper_.AddPaths(solution, ptSubject, true);
clipper_.Execute(ctIntersection, solution);
clipper_.removeSubject();
region.points = solution;
std::string type = region.isLayer
? *utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
void visitArea(const utymap::entities::Area& area)
{
Style style = context_.styleProvider.forElement(area, context_.quadKey.levelOfDetail);
Region region = createRegion(style, area.coordinates);
std::string type = region.isLayer
? *utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
void visitRelation(const utymap::entities::Relation& relation)
{
Region region;
struct RelationVisitor : public ElementVisitor
{
const Relation& relation;
TerraBuilder::TerraBuilderImpl& builder;
Region& region;
RelationVisitor(TerraBuilder::TerraBuilderImpl& builder, const Relation& relation, Region& region) :
builder(builder), relation(relation), region(region) {}
void visitNode(const utymap::entities::Node& n) { n.accept(builder); }
void visitWay(const utymap::entities::Way& w) { w.accept(builder); }
void visitArea(const utymap::entities::Area& a)
{
Path path;
path.reserve(a.coordinates.size());
for (const GeoCoordinate& c : a.coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
}
void visitRelation(const utymap::entities::Relation& r) { r.accept(builder); }
} visitor(*this, relation, region);
for (const auto& element : relation.elements) {
// if there are no tags, then this element is result of clipping
if (element->tags.empty())
element->tags = relation.tags;
element->accept(visitor);
}
if (!region.points.empty()) {
Style style = context_.styleProvider.forElement(relation, context_.quadKey.levelOfDetail);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
std::string type = region.isLayer
? *utymap::utils::getString(TerrainLayerKey, context_.stringTable, style)
: "";
layers_[type].push_back(region);
}
}
// builds tile mesh using data provided.
void complete()
{
clipper_.Clear();
buildLayers();
buildBackground();
context_.meshCallback(mesh_);
}
private:
// process all found layers.
void buildLayers()
{
// 1. process layers: regions with shared properties.
std::stringstream ss(*utymap::utils::getString(LayerPriorityKey, context_.stringTable, style_));
while (ss.good()) {
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
buildFromRegions(layer->second, createMeshOptions(style_, name + "-"));
layers_.erase(layer);
}
}
// 2. Process the rest: each region has aready its own properties.
for (auto& layer : layers_)
for (auto& region : layer.second) {
buildFromPaths(region.points, region.options);
}
}
// process the rest area.
void buildBackground()
{
clipper_.AddPath(tileRect_, ptSubject, true);
Paths background;
clipper_.Execute(ctDifference, background, pftPositive, pftPositive);
clipper_.Clear();
if (!background.empty())
populateMesh(createMeshOptions(style_, ""), background);
}
Region createRegion(const Style& style, const std::vector<GeoCoordinate>& coordinates)
{
Region region;
Path path;
path.reserve(coordinates.size());
for (const GeoCoordinate& c : coordinates)
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
region.points.push_back(path);
region.isLayer = style.has(context_.stringTable.getId(TerrainLayerKey));
if (!region.isLayer)
region.options = createMeshOptions(style, "");
return std::move(region);
}
std::shared_ptr<MeshBuilder::Options> createMeshOptions(const Style& style, const std::string& prefix)
{
double quadKeyWidth = bbox_.maxPoint.latitude - bbox_.minPoint.latitude;
auto gradientKey = utymap::utils::getString(prefix + GradientKey, context_.stringTable, style);
return std::shared_ptr<MeshBuilder::Options>(new MeshBuilder::Options(
utymap::utils::getDimension(prefix + MaxAreaKey, context_.stringTable, style, quadKeyWidth * quadKeyWidth),
utymap::utils::getDouble(prefix + EleNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDouble(prefix + ColorNoiseFreqKey, context_.stringTable, style),
utymap::utils::getDimension(prefix + HeightKey, context_.stringTable, style, quadKeyWidth, 0),
context_.styleProvider.getGradient(*gradientKey),
std::numeric_limits<double>::lowest(),
*utymap::utils::getString(prefix + MeshNameKey, context_.stringTable, style, ""),
/* no new vertices on boundaries */ 1));
}
void buildFromRegions(const Regions& regions, const std::shared_ptr<MeshBuilder::Options>& options)
{
// merge all regions together
Clipper clipper;
for (const Region& region : regions)
clipper.AddPaths(region.points, ptSubject, true);
Paths result;
clipper.Execute(ctUnion, result, pftPositive, pftPositive);
buildFromPaths(result, options);
}
void buildFromPaths(Paths& paths, const std::shared_ptr<MeshBuilder::Options>& options)
{
clipper_.AddPaths(paths, ptSubject, true);
paths.clear();
clipper_.Execute(ctDifference, paths, pftPositive, pftPositive);
clipper_.moveSubjectToClip();
populateMesh(options, paths);
}
void populateMesh(const std::shared_ptr<MeshBuilder::Options>& options, Paths& paths)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = std::abs(options->heightOffset) > 1E-8;
// calculate approximate size of overall points
auto size = 0;
for (auto i = 0; i < paths.size(); ++i)
size += paths[i].size() * 1.5;
Polygon polygon(size);
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
bool isHole = area < 0;
if (std::abs(area) < AreaTolerance)
continue;
Points points = restorePoints(path);
if (isHole)
polygon.addHole(points);
else
polygon.addContour(points);
if (hasHeightOffset)
processHeightOffset(options, points, isHole);
}
if (!polygon.points.empty())
fillMesh(options, polygon);
}
// restores mesh points from clipper points and injects new ones according to grid.
Points restorePoints(const Path& path)
{
int lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++)
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
return std::move(points);
}
void fillMesh(const std::shared_ptr<MeshBuilder::Options>& options, Polygon& polygon)
{
if (options->meshName != "") {
Mesh polygonMesh(options->meshName);
context_.meshBuilder.addPolygon(polygonMesh, polygon, *options);
context_.meshCallback(polygonMesh);
}
else {
context_.meshBuilder.addPolygon(mesh_, polygon, *options);
}
}
void processHeightOffset(const std::shared_ptr<MeshBuilder::Options>& options, const Points& points, bool isHole)
{
auto index = mesh_.vertices.size() / 3;
// do not use elevation noise for height offset.
auto newOptions = *options;
newOptions.eleNoiseFreq = 0;
for (auto i = 0; i < points.size(); ++i) {
Point p1 = points[i];
Point p2 = points[i == (points.size() - 1) ? 0 : i + 1];
// check whether two points are on cell rect
if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2))
continue;
context_.meshBuilder.addPlane(mesh_, p1, p2, newOptions);
}
}
const Style style_;
ClipperEx clipper_;
ClipperOffset offset_;
LineGridSplitter splitter_;
BoundingBox bbox_;
Rectangle rect_;
Path tileRect_;
Layers layers_;
Mesh mesh_;
};
void TerraBuilder::visitNode(const utymap::entities::Node& node) { pimpl_->visitNode(node); }
void TerraBuilder::visitWay(const utymap::entities::Way& way) { pimpl_->visitWay(way); }
void TerraBuilder::visitArea(const utymap::entities::Area& area) { pimpl_->visitArea(area); }
void TerraBuilder::visitRelation(const utymap::entities::Relation& relation) { pimpl_->visitRelation(relation); }
void TerraBuilder::complete() { pimpl_->complete(); }
TerraBuilder::~TerraBuilder() { }
TerraBuilder::TerraBuilder(const BuilderContext& context) :
utymap::builders::ElementBuilder(context),
pimpl_(new TerraBuilder::TerraBuilderImpl(context))
{
}
<|endoftext|>
|
<commit_before>/*
* @file filesystem-lru-cache.cc
* @brief additional implementation of file system LRU cache
*
* @date Nov 20, 2014
* @author elenav
*/
#include <map>
#include <boost/regex.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include "dfs_cache/cache-mgr.hpp"
#include "dfs_cache/filesystem-lru-cache.hpp"
#include "dfs_cache/utilities.hpp"
namespace impala{
bool FileSystemLRUCache::deleteFile(managed_file::File* file, bool physically){
// preserve path for future usage:
std::string path = file->fqp();
{
std::lock_guard<std::mutex> lock(m_deletionsmux);
// add the item into deletions list
m_deletionList.push_back(file->fqp());
}
// notify deletion action is scheduled
m_deletionHappensCondition.notify_all();
// for physical removal scenario, drop the file from file system
if (physically) {
LOG (INFO) << "File \"" << file->fqp() << "\" is near to be removed from the disk." << "\n";
// delegate further deletion scenario to the file itself:
file->drop();
}
// get rid of file metadata object:
delete file;
{
std::lock_guard<std::mutex> lock(m_deletionsmux);
// now drop the file from deletions list:
m_deletionList.remove(path);
}
// notify deletion happens
m_deletionHappensCondition.notify_all();
return true;
}
bool FileSystemLRUCache::deletePath(const std::string& path){
boost::filesystem::recursive_directory_iterator end_iter;
// collection to hold files under the path:
typedef std::vector<boost::filesystem::path> files;
typedef std::vector<boost::filesystem::path>::iterator files_it;
files _files;
bool ret = true;
if (!boost::filesystem::exists(path))
return false;
// if path is the directory:
if (boost::filesystem::is_directory(path)){
for (boost::filesystem::recursive_directory_iterator dir_iter(path);
dir_iter != end_iter; ++dir_iter) {
if (boost::filesystem::is_regular_file(dir_iter->status())) {
_files.push_back(*dir_iter);
}
}
files_it it = _files.begin();
if (it == _files.end())
return true;
for (; it != _files.end(); it++) {
// drop all files:
ret = ret && remove((*it).string(), true);
}
// if all files were removed, its safe to remove the path completely
if(ret)
boost::filesystem::remove_all(path);
return ret;
}
// the path is a file, so just remove it physically
return remove(path, true);
}
void FileSystemLRUCache::sync(managed_file::File* file){
// if file is not valid, break the handler
if (file == nullptr || !file->valid())
return;
// and wait for prepare operation will be finished:
DataSet data;
data.push_back(file->relative_name().c_str());
bool condition = false;
boost::condition_variable condition_var;
boost::mutex completion_mux;
status::StatusInternal cbStatus;
PrepareCompletedCallback cb =
[&] (SessionContext context,
const std::list<boost::shared_ptr<FileProgress> > & progress,
request_performance const & performance, bool overall,
bool canceled, taskOverallStatus status) -> void {
cbStatus = (status == taskOverallStatus::COMPLETED_OK ? status::StatusInternal::OK : status::StatusInternal::REQUEST_FAILED);
if(status != taskOverallStatus::COMPLETED_OK) {
LOG (ERROR) << "Failed to load file \"" << file->fqp() << "\"" << ". Status : "
<< status << ".\n";
file->state(managed_file::State::FILE_IS_FORBIDDEN);
}
if(context == NULL)
LOG (ERROR) << "NULL context received while loading the file \"" << file->fqp()
<< "\"" << ".Status : " << status << ".\n";
if(progress.size() != data.size())
LOG (ERROR) << "Expected amount of progress is not equal to received for file \""
<< file->fqp() << "\"" << ".Status : " << status << ".\n";
if(!overall)
LOG (ERROR) << "Overall task status is failure.\""
<< file->fqp() << "\"" << ".Status : " << status << ".\n";
boost::lock_guard<boost::mutex> lock(completion_mux);
condition = true;
condition_var.notify_one();
};
requestIdentity identity;
auto f1 = std::bind(&CacheManager::cachePrepareData,
CacheManager::instance(), ph::_1, ph::_2, ph::_3, ph::_4, ph::_5);
boost::uuids::uuid uuid = boost::uuids::random_generator()();
std::string local_client = boost::lexical_cast<std::string>(uuid);
SessionContext ctx = static_cast<void*>(&local_client);
status::StatusInternal status;
FileSystemDescriptor fsDescriptor;
fsDescriptor.dfs_type = file->origin();
fsDescriptor.host = file->host();
try {
fsDescriptor.port = std::stoi(file->port());
} catch (...) {
return;
}
// execute request in async way to utilize requests pool:
status = f1(ctx, std::cref(fsDescriptor), std::cref(data), cb,
std::ref(identity));
// check operation scheduling status:
if (status != status::StatusInternal::OPERATION_ASYNC_SCHEDULED) {
LOG (ERROR)<< "Prepare request - failed to schedule - for \"" << file->fqnp() << "\"" << ". Status : "
<< status << ".\n";
// no need to wait for callback to fire, operation was not scheduled
return;
}
// wait when completion callback will be fired by Prepare scenario:
boost::unique_lock<boost::mutex> lock(completion_mux);
condition_var.wait(lock, [&] {return condition;});
lock.unlock();
// check callback status:
if (cbStatus != status::StatusInternal::OK) {
LOG (ERROR)<< "Prepare request failed for \"" << file->fqnp() << "\"" << ". Status : "
<< cbStatus << ".\n";
file->state(managed_file::State::FILE_IS_FORBIDDEN);
return;
}
file->state(managed_file::State::FILE_HAS_CLIENTS);
}
bool FileSystemLRUCache::reload(const std::string& root){
if(root.empty())
return false;
m_root = root;
boost::filesystem::recursive_directory_iterator end_iter;
// sort files in the root in ascending order basing on their timestamp:
typedef std::multimap<std::time_t, boost::filesystem::path> last_access_multi;
// iterator for sorted collection:
typedef std::multimap<std::time_t, boost::filesystem::path>::iterator last_access_multi_it;
last_access_multi result_set;
// note that std::time_t accurate to a second
if ( boost::filesystem::exists(m_root) && boost::filesystem::is_directory(m_root)){
for( boost::filesystem::recursive_directory_iterator dir_iter(m_root) ; dir_iter != end_iter ; ++dir_iter){
if (boost::filesystem::is_regular_file(dir_iter->status()) ){
result_set.insert(last_access_multi::value_type(boost::filesystem::last_write_time(dir_iter->path()), *dir_iter));
}
}
}
// reset the underlying LRU cache.
reset();
last_access_multi_it it = result_set.begin();
if(it == result_set.end()){
// leave start time default (now)
return true;
}
// reload most old timestamp:
m_startTime = boost::posix_time::from_time_t((*it).first);
// and populate sorted root content:
for(; it != result_set.end(); it++){
std::string lp = (*it).second.string();
// create the managed file instance if there's network path can be successfully restored from its name
// so that the file can be managed by Imapla-To-Go:
std::string fqnp;
std::string relative;
FileSystemDescriptor desciptor = managed_file::File::restoreNetworkPathFromLocal(lp, fqnp, relative);
if(!desciptor.valid)
continue; // do not register this file
managed_file::File* file;
// and add it into the cache
add(lp, file, managed_file::NatureFlag::PHYSICAL);
// and mark the file as "idle":
file->state(managed_file::State::FILE_IS_IDLE);
}
return true;
}
managed_file::File* FileSystemLRUCache::find(std::string path) {
// first find the file within the registry
managed_file::File* file = m_idxFileLocalPath->operator [](path);
if(file == nullptr)
return file;
std::unique_lock<std::mutex> lock(m_deletionsmux);
// check whether the requested file is under finalization maybe?
bool under_finalization = std::find(m_deletionList.begin(), m_deletionList.end(), path) != m_deletionList.end();
// if file is under finalization already or was unable to be opened, wait while it will be finalized
// and then reclaim it. open() should be called while collection of "deletions" is locked to prevent the dangling pointer reference
if(under_finalization || (file->open() != status::StatusInternal::OK)){
LOG(WARNING) << "File \"" << path << "\" is under finalization and cannot be used. "
<< "Waiting for it to be removed before to reinvoke its preparation.\n";
// Check the active deletions list, if the file is there, do not use it and reclaim it for reload when deletion completes:
std::list<std::string>::iterator it;
m_deletionHappensCondition.wait(lock, [&] {
it = std::find(m_deletionList.begin(), m_deletionList.end(), path);
return it == m_deletionList.end();
}
);
lock.unlock();
// reclaim the file:
file = m_idxFileLocalPath->operator [](path);
if(file == nullptr)
return nullptr;
return file;
}
// unlock deletions list, will work only if alive file was "opened" successfully
lock.unlock();
// if file is "forbidden but the time between sync attempts elapsed", it should be resync.
// prevent outer world from usage of invalid:
// if file state is "FORBIDDEN" (which means the file was not synchronized locally successfully on last attempt)
if(file->state() == managed_file::State::FILE_IS_FORBIDDEN){
// resync the file if the time between sync attempts elapsed:
if(file->shouldtryresync()){
sync(file);
}
}
return file;
}
bool FileSystemLRUCache::add(std::string path, managed_file::File*& file, managed_file::NatureFlag creationFlag){
bool duplicate = false;
bool success = false;
// we create and destruct File objects only here, in LRU cache layer
file = new managed_file::File(path.c_str(), m_weightChangedPredicate, creationFlag, m_getFileInfoPredicate, m_freeFileInfoPredicate);
// increase refcount to this file before being shared to outer world
file->open();
// when item is externally injected to the cache, it should have time "now"
success = LRUCache<managed_file::File>::add(file, duplicate);
if(duplicate){
LOG(WARNING) << "Attempt to add the duplicate to the cache, path = \"" << path << "\"\n";
// no need for this file, get the rid of
delete file;
}
if(!success)
LOG (WARNING) << "new file \"" << path << "\" could not be added into the cache, reason : no free space available.\n";
return success;
}
void FileSystemLRUCache::handleCapacityChanged(long long size_delta){
if(size_delta == 0)
return;
if(size_delta > 0)
std::atomic_fetch_add_explicit(&m_currentCapacity, size_delta, std::memory_order_relaxed);
else
std::atomic_fetch_sub_explicit(&m_currentCapacity, size_delta, std::memory_order_relaxed);
}
}
<commit_msg>adding some logs on cache startup flow<commit_after>/*
* @file filesystem-lru-cache.cc
* @brief additional implementation of file system LRU cache
*
* @date Nov 20, 2014
* @author elenav
*/
#include <map>
#include <boost/regex.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include "dfs_cache/cache-mgr.hpp"
#include "dfs_cache/filesystem-lru-cache.hpp"
#include "dfs_cache/utilities.hpp"
namespace impala{
bool FileSystemLRUCache::deleteFile(managed_file::File* file, bool physically){
// preserve path for future usage:
std::string path = file->fqp();
{
std::lock_guard<std::mutex> lock(m_deletionsmux);
// add the item into deletions list
m_deletionList.push_back(file->fqp());
}
// notify deletion action is scheduled
m_deletionHappensCondition.notify_all();
// for physical removal scenario, drop the file from file system
if (physically) {
LOG (INFO) << "File \"" << file->fqp() << "\" is near to be removed from the disk." << "\n";
// delegate further deletion scenario to the file itself:
file->drop();
}
// get rid of file metadata object:
delete file;
{
std::lock_guard<std::mutex> lock(m_deletionsmux);
// now drop the file from deletions list:
m_deletionList.remove(path);
}
// notify deletion happens
m_deletionHappensCondition.notify_all();
return true;
}
bool FileSystemLRUCache::deletePath(const std::string& path){
boost::filesystem::recursive_directory_iterator end_iter;
// collection to hold files under the path:
typedef std::vector<boost::filesystem::path> files;
typedef std::vector<boost::filesystem::path>::iterator files_it;
files _files;
bool ret = true;
if (!boost::filesystem::exists(path))
return false;
// if path is the directory:
if (boost::filesystem::is_directory(path)){
for (boost::filesystem::recursive_directory_iterator dir_iter(path);
dir_iter != end_iter; ++dir_iter) {
if (boost::filesystem::is_regular_file(dir_iter->status())) {
_files.push_back(*dir_iter);
}
}
files_it it = _files.begin();
if (it == _files.end())
return true;
for (; it != _files.end(); it++) {
// drop all files:
ret = ret && remove((*it).string(), true);
}
// if all files were removed, its safe to remove the path completely
if(ret)
boost::filesystem::remove_all(path);
return ret;
}
// the path is a file, so just remove it physically
return remove(path, true);
}
void FileSystemLRUCache::sync(managed_file::File* file){
// if file is not valid, break the handler
if (file == nullptr || !file->valid())
return;
// and wait for prepare operation will be finished:
DataSet data;
data.push_back(file->relative_name().c_str());
bool condition = false;
boost::condition_variable condition_var;
boost::mutex completion_mux;
status::StatusInternal cbStatus;
PrepareCompletedCallback cb =
[&] (SessionContext context,
const std::list<boost::shared_ptr<FileProgress> > & progress,
request_performance const & performance, bool overall,
bool canceled, taskOverallStatus status) -> void {
cbStatus = (status == taskOverallStatus::COMPLETED_OK ? status::StatusInternal::OK : status::StatusInternal::REQUEST_FAILED);
if(status != taskOverallStatus::COMPLETED_OK) {
LOG (ERROR) << "Failed to load file \"" << file->fqp() << "\"" << ". Status : "
<< status << ".\n";
file->state(managed_file::State::FILE_IS_FORBIDDEN);
}
if(context == NULL)
LOG (ERROR) << "NULL context received while loading the file \"" << file->fqp()
<< "\"" << ".Status : " << status << ".\n";
if(progress.size() != data.size())
LOG (ERROR) << "Expected amount of progress is not equal to received for file \""
<< file->fqp() << "\"" << ".Status : " << status << ".\n";
if(!overall)
LOG (ERROR) << "Overall task status is failure.\""
<< file->fqp() << "\"" << ".Status : " << status << ".\n";
boost::lock_guard<boost::mutex> lock(completion_mux);
condition = true;
condition_var.notify_one();
};
requestIdentity identity;
auto f1 = std::bind(&CacheManager::cachePrepareData,
CacheManager::instance(), ph::_1, ph::_2, ph::_3, ph::_4, ph::_5);
boost::uuids::uuid uuid = boost::uuids::random_generator()();
std::string local_client = boost::lexical_cast<std::string>(uuid);
SessionContext ctx = static_cast<void*>(&local_client);
status::StatusInternal status;
FileSystemDescriptor fsDescriptor;
fsDescriptor.dfs_type = file->origin();
fsDescriptor.host = file->host();
try {
fsDescriptor.port = std::stoi(file->port());
} catch (...) {
return;
}
// execute request in async way to utilize requests pool:
status = f1(ctx, std::cref(fsDescriptor), std::cref(data), cb,
std::ref(identity));
// check operation scheduling status:
if (status != status::StatusInternal::OPERATION_ASYNC_SCHEDULED) {
LOG (ERROR)<< "Prepare request - failed to schedule - for \"" << file->fqnp() << "\"" << ". Status : "
<< status << ".\n";
// no need to wait for callback to fire, operation was not scheduled
return;
}
// wait when completion callback will be fired by Prepare scenario:
boost::unique_lock<boost::mutex> lock(completion_mux);
condition_var.wait(lock, [&] {return condition;});
lock.unlock();
// check callback status:
if (cbStatus != status::StatusInternal::OK) {
LOG (ERROR)<< "Prepare request failed for \"" << file->fqnp() << "\"" << ". Status : "
<< cbStatus << ".\n";
file->state(managed_file::State::FILE_IS_FORBIDDEN);
return;
}
file->state(managed_file::State::FILE_HAS_CLIENTS);
}
bool FileSystemLRUCache::reload(const std::string& root){
if(root.empty())
return false;
m_root = root;
LOG (INFO) << "Going to reload the cache from configured \"" << root << "\" directory.\n";
boost::filesystem::recursive_directory_iterator end_iter;
// sort files in the root in ascending order basing on their timestamp:
typedef std::multimap<std::time_t, boost::filesystem::path> last_access_multi;
// iterator for sorted collection:
typedef std::multimap<std::time_t, boost::filesystem::path>::iterator last_access_multi_it;
last_access_multi result_set;
// note that std::time_t accurate to a second
if ( boost::filesystem::exists(m_root) && boost::filesystem::is_directory(m_root)){
for( boost::filesystem::recursive_directory_iterator dir_iter(m_root) ; dir_iter != end_iter ; ++dir_iter){
if (boost::filesystem::is_regular_file(dir_iter->status()) ){
result_set.insert(last_access_multi::value_type(boost::filesystem::last_write_time(dir_iter->path()), *dir_iter));
}
}
}
// reset the underlying LRU cache.
reset();
last_access_multi_it it = result_set.begin();
if(it == result_set.end()){
// leave start time default (now)
return true;
}
// reload most old timestamp:
m_startTime = boost::posix_time::from_time_t((*it).first);
// and populate sorted root content:
for(; it != result_set.end(); it++){
std::string lp = (*it).second.string();
// create the managed file instance if there's network path can be successfully restored from its name
// so that the file can be managed by Imapla-To-Go:
std::string fqnp;
std::string relative;
FileSystemDescriptor desciptor = managed_file::File::restoreNetworkPathFromLocal(lp, fqnp, relative);
if(!desciptor.valid)
continue; // do not register this file
LOG (INFO) << "Reload : Cached file \"" << fqnp << "\" is near to be added to the cache.\n";
managed_file::File* file;
// and add it into the cache
add(lp, file, managed_file::NatureFlag::PHYSICAL);
// and mark the file as "idle":
file->state(managed_file::State::FILE_IS_IDLE);
}
return true;
}
managed_file::File* FileSystemLRUCache::find(std::string path) {
// first find the file within the registry
managed_file::File* file = m_idxFileLocalPath->operator [](path);
if(file == nullptr)
return file;
std::unique_lock<std::mutex> lock(m_deletionsmux);
// check whether the requested file is under finalization maybe?
bool under_finalization = std::find(m_deletionList.begin(), m_deletionList.end(), path) != m_deletionList.end();
// if file is under finalization already or was unable to be opened, wait while it will be finalized
// and then reclaim it. open() should be called while collection of "deletions" is locked to prevent the dangling pointer reference
if(under_finalization || (file->open() != status::StatusInternal::OK)){
LOG(WARNING) << "File \"" << path << "\" is under finalization and cannot be used. "
<< "Waiting for it to be removed before to reinvoke its preparation.\n";
// Check the active deletions list, if the file is there, do not use it and reclaim it for reload when deletion completes:
std::list<std::string>::iterator it;
m_deletionHappensCondition.wait(lock, [&] {
it = std::find(m_deletionList.begin(), m_deletionList.end(), path);
return it == m_deletionList.end();
}
);
lock.unlock();
// reclaim the file:
file = m_idxFileLocalPath->operator [](path);
if(file == nullptr)
return nullptr;
return file;
}
// unlock deletions list, will work only if alive file was "opened" successfully
lock.unlock();
// if file is "forbidden but the time between sync attempts elapsed", it should be resync.
// prevent outer world from usage of invalid:
// if file state is "FORBIDDEN" (which means the file was not synchronized locally successfully on last attempt)
if(file->state() == managed_file::State::FILE_IS_FORBIDDEN){
// resync the file if the time between sync attempts elapsed:
if(file->shouldtryresync()){
sync(file);
}
}
return file;
}
bool FileSystemLRUCache::add(std::string path, managed_file::File*& file, managed_file::NatureFlag creationFlag){
bool duplicate = false;
bool success = false;
// we create and destruct File objects only here, in LRU cache layer
file = new managed_file::File(path.c_str(), m_weightChangedPredicate, creationFlag, m_getFileInfoPredicate, m_freeFileInfoPredicate);
// increase refcount to this file before being shared to outer world
file->open();
// when item is externally injected to the cache, it should have time "now"
success = LRUCache<managed_file::File>::add(file, duplicate);
if(duplicate){
LOG(WARNING) << "Attempt to add the duplicate to the cache, path = \"" << path << "\"\n";
// no need for this file, get the rid of
delete file;
}
if(!success)
LOG (WARNING) << "new file \"" << path << "\" could not be added into the cache, reason : no free space available.\n";
return success;
}
void FileSystemLRUCache::handleCapacityChanged(long long size_delta){
if(size_delta == 0)
return;
if(size_delta > 0)
std::atomic_fetch_add_explicit(&m_currentCapacity, size_delta, std::memory_order_relaxed);
else
std::atomic_fetch_sub_explicit(&m_currentCapacity, size_delta, std::memory_order_relaxed);
}
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <iostream>
// euclidean distance
double distance(std::pair<double, double>, std::pair<double, double>);
double distance(std::pair<int, int>, std::pair<int, int>);
int shortest_path_dist(vector< vector<int> >);
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "I needs a file dammit! << std::endl;
return 1;
}
std::fstream f(argv[1]);
// well what now?
// something about an algorithm...
// oh yes! i think i need to build the distance array
// call shortest path with it
// then print out the answer
std::cout << answer << std::endl;
}
int shortest_path_dist(std::vector< std::vector<int> > dist)
{
// for each iteration
// for each ant : IN PARALLEL
// start a new thread,initialize the ant
// share distance and pheromone graph for the thread
// while a tour is not finished
// choose the next city (eq 1,2)
// atomic: local pheromone update (eq 3)
// end while // end of ant's travel
// atomic: global pheromone update (eq 4)
// terminate the thread, release resources
// end for
// end for // end of iteration
}
<commit_msg>Fixed some of the psuedocode.<commit_after>#include <vector>
#include <iostream>
// euclidean distance
double distance(std::pair<double, double>, std::pair<double, double>);
double distance(std::pair<int, int>, std::pair<int, int>);
int shortest_path_dist(vector< vector<int> >);
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "I needs a file dammit! << std::endl;
return 1;
}
std::fstream f(argv[1]);
// well what now?
// something about an algorithm...
// oh yes! i think i need to build the distance array
// call shortest path with it
// then print out the answer
std::cout << answer << std::endl;
}
int shortest_path_dist(std::vector< std::vector<int> > dist)
{
// start all needed threads
// for each iteration
// for each ant : IN PARALLEL
// initialize the ant
// share distance and pheromone graph for the thread
// while a tour is not finished
// choose the next city (eq 1,2)
// atomic: local pheromone update (eq 3)
// end while // end of ant's travel
// atomic: global pheromone update (eq 4)
// terminate the thread, release resources
// end for
// barrier: all ants
// end for // end of iteration
}
<|endoftext|>
|
<commit_before>// Author: Brian Scully
// Copyright (c) 2016 Agponics
#include "ds18b20_sensor.h"
void CDs18b20Sensor::set_pin(int pin)
{
CDevice::set_pin(pin);
m_one_wire = OneWire(pin);
m_dt = DallasTemperature(&m_one_wire);
m_dt.begin();
}
String CDs18b20Sensor::get_status_str()
{
double temp = 0.0;
uint8_t probe_cnt = 0;
String out = "";
// have all probes read temp
m_dt.requestTemperatures();
probe_cnt = m_dt.getDeviceCount();
for (uint8_t i = 0; i < probe_cnt; i++)
{
float temp_celsius = m_dt.getTempCByIndex(i);
out += CDevice::get_status_str();
out += "probe" + String(i) + ":temp:";
out += String(int(celsius_to_fahrenheit(temp_celsius)));
out += "\n";
}
return out;
}
String CDs18b20Sensor::get_addrs()
{
uint8_t next_addr[8] = {0};
uint8_t i = 0;
String out = "One-wire Addresses Found:\n";
while (m_dt.getAddress(next_addr, i))
{
out += String(i) + ":";
for (int j = 0; j < 8; j++)
{
out += " 0x" + String(next_addr[j], HEX);
}
out += "\n";
i++;
}
return out;
}
<commit_msg>Switch to DT Fahrenheit call<commit_after>// Author: Brian Scully
// Copyright (c) 2016 Agponics
#include "ds18b20_sensor.h"
void CDs18b20Sensor::set_pin(int pin)
{
CDevice::set_pin(pin);
m_one_wire = OneWire(pin);
m_dt = DallasTemperature(&m_one_wire);
m_dt.begin();
}
String CDs18b20Sensor::get_status_str()
{
double temp = 0.0;
uint8_t probe_cnt = 0;
String out = "";
// have all probes read temp
m_dt.requestTemperatures();
probe_cnt = m_dt.getDeviceCount();
for (uint8_t i = 0; i < probe_cnt; i++)
{
temp = m_dt.getTempFByIndex(i);
out += CDevice::get_status_str();
out += "probe" + String(i) + ":temp:";
out += String(int(temp));
out += "\n";
}
return out;
}
String CDs18b20Sensor::get_addrs()
{
uint8_t next_addr[8] = {0};
uint8_t i = 0;
String out = "One-wire Addresses Found:\n";
while (m_dt.getAddress(next_addr, i))
{
out += String(i) + ":";
for (int j = 0; j < 8; j++)
{
out += " 0x" + String(next_addr[j], HEX);
}
out += "\n";
i++;
}
return out;
}
<|endoftext|>
|
<commit_before>/** \brief Classes related to the Zotero Harvester's interoperation with the Zeder database
* \author Madeeswaran Kannan
*
* \copyright 2020-2021 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ZoteroHarvesterZederInterop.h"
#include <cmath>
#include "util.h"
namespace ZoteroHarvester {
namespace ZederInterop {
const std::map<Config::JournalParams::IniKey, std::string> INI_KEY_TO_ZEDER_COLUMN_MAP {
{ Config::JournalParams::IniKey::NAME, "tit" },
{ Config::JournalParams::IniKey::ONLINE_PPN, "eppn" },
{ Config::JournalParams::IniKey::PRINT_PPN, "pppn" },
{ Config::JournalParams::IniKey::ONLINE_ISSN, "essn" },
{ Config::JournalParams::IniKey::PRINT_ISSN, "issn" },
{ Config::JournalParams::IniKey::EXPECTED_LANGUAGES, "sprz" },
{ Config::JournalParams::IniKey::SSGN, "ber" },
{ Config::JournalParams::IniKey::LICENSE, "oacc" },
{ Config::JournalParams::IniKey::PERSONALIZED_AUTHORS, "tiefp"},
// The following two columns/INI keys are intentionally excluded as they are special cases.
// Even though there is a one-to-one correspondence for each to the two columns,
// they are stored differently in memory (in the Zeder::Entry class) than all other
// columns. Therefore, they can't be trivially mapped to each other.
// { Config::JournalParams::IniKey::ZEDER_ID, "Z" },
// { Config::JournalParams::IniKey::ZEDER_MODIFIED_TIME, "Mtime" },
};
static std::string ResolveGroup(const Zeder::Entry &/*unused*/, const Zeder::Flavour zeder_flavour) {
return Zeder::FLAVOUR_TO_STRING_MAP.at(zeder_flavour);
}
static std::string ResolveEntryPointURL(const Zeder::Entry &zeder_entry, const Zeder::Flavour zeder_flavour) {
const auto &rss(zeder_entry.getAttribute("rss", ""));
const auto &p_zot2(zeder_entry.getAttribute("p_zot2", ""));
const auto &url1(zeder_entry.getAttribute("url1", ""));
const auto &url2(zeder_entry.getAttribute("url2", ""));
// Field priorities differ between IxTheo and KrimDok (based on who updated which field first)
switch (zeder_flavour) {
case Zeder::Flavour::IXTHEO:
if (not rss.empty())
return rss;
else if (not p_zot2.empty())
return p_zot2;
else if (not url2.empty())
return url2;
else
return url1;
case Zeder::Flavour::KRIMDOK:
if (not rss.empty())
return rss;
else if (not url2.empty())
return url2;
else if (not p_zot2.empty())
return p_zot2;
else
return url1;
default:
return "";
}
}
static std::string ResolveHarvesterOperation(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
const auto &z_type(zeder_entry.getAttribute("z_type"));
if (z_type == "rss")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::RSS);
else if (z_type == "crawl")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::CRAWL);
else if (z_type == "email")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::EMAIL);
else if (z_type == "api")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::APIQUERY);
else if (z_type == "") { /* Fall back to old approach if not set */
const auto &rss(zeder_entry.getAttribute("rss", ""));
if (not rss.empty())
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::RSS);
else
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::CRAWL);
} else
LOG_ERROR("Invalid Harvester operation value \"" + z_type + "\" for in field z_type");
}
std::string ResolveUploadOperation(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
if (zeder_entry.getAttribute("prodf", "") == "zota")
return Config::UPLOAD_OPERATION_TO_STRING_MAP.at(Config::UploadOperation::LIVE);
const std::string prode(zeder_entry.getAttribute("prode", ""));
if (prode == "zotat" or prode == "zota")
return Config::UPLOAD_OPERATION_TO_STRING_MAP.at(Config::UploadOperation::TEST);
return Config::UPLOAD_OPERATION_TO_STRING_MAP.at(Config::UploadOperation::NONE);
}
static std::string ResolveUpdateWindow(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
// Calculate an admissible range in days for a frequency given per year.
// Right now we simply ignore entries that cannot be suitably converted to float.
float frequency_as_float;
if (not StringUtil::ToFloat(zeder_entry.getAttribute("freq", ""), &frequency_as_float))
return "";
float admissible_range = (365 / frequency_as_float) * 1.5;
return std::to_string(static_cast<int>(std::round(admissible_range)));
}
static std::string ResolveSelectiveEvaluation(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
if (zeder_entry.getAttribute("ausw", "") == "selek")
return "true";
else
return "false";
}
const std::map<Config::JournalParams::IniKey, std::function<std::string(const Zeder::Entry &, const Zeder::Flavour)>> INI_KEY_TO_ZEDER_RESOLVER_MAP {
{ Config::JournalParams::IniKey::GROUP, ResolveGroup },
{ Config::JournalParams::IniKey::ENTRY_POINT_URL, ResolveEntryPointURL },
{ Config::JournalParams::IniKey::HARVESTER_OPERATION, ResolveHarvesterOperation },
{ Config::JournalParams::IniKey::UPLOAD_OPERATION, ResolveUploadOperation },
{ Config::JournalParams::IniKey::UPDATE_WINDOW, ResolveUpdateWindow },
{ Config::JournalParams::IniKey::SELECTIVE_EVALUATION, ResolveSelectiveEvaluation },
};
static inline bool IsValidZederValue(const std::string &zeder_value) {
return zeder_value != "NV";
}
std::string GetJournalParamsIniValueFromZederEntry(const Zeder::Entry &zeder_entry, const Zeder::Flavour zeder_flavour,
const Config::JournalParams::IniKey ini_key)
{
std::string zeder_value;
if (INI_KEY_TO_ZEDER_COLUMN_MAP.find(ini_key) != INI_KEY_TO_ZEDER_COLUMN_MAP.end())
zeder_value = zeder_entry.getAttribute(INI_KEY_TO_ZEDER_COLUMN_MAP.at(ini_key), "");
else if (INI_KEY_TO_ZEDER_RESOLVER_MAP.find(ini_key) != INI_KEY_TO_ZEDER_RESOLVER_MAP.end())
zeder_value = INI_KEY_TO_ZEDER_RESOLVER_MAP.at(ini_key)(zeder_entry, zeder_flavour);
else
LOG_ERROR("unable to resolve value from Zeder entry for INI key '" + Config::JournalParams::GetIniKeyString(ini_key) + "'");
zeder_value = TextUtil::CollapseAndTrimWhitespace(zeder_value);
if (IsValidZederValue(zeder_value))
return zeder_value;
else
return "";
}
static Zeder::Flavour GetZederInstanceFromGroupName(const std::string &group_name, const std::string &journal_name = "") {
if (::strcasecmp(group_name.c_str(), "ixtheo") == 0)
return Zeder::Flavour::IXTHEO;
else if (::strcasecmp(group_name.c_str(), "relbib") == 0)
return Zeder::Flavour::IXTHEO;
else if (::strcasecmp(group_name.c_str(), "krimdok") == 0)
return Zeder::Flavour::KRIMDOK;
if (not journal_name.empty())
LOG_ERROR("group '" + group_name + "' for journal '" + journal_name + "' could not be assigned to either Zeder instance");
else
LOG_ERROR("group '" + group_name + "' could not be assigned to either Zeder instance");
}
Zeder::Flavour GetZederInstanceForJournal(const Config::JournalParams &journal_params) {
return GetZederInstanceFromGroupName(journal_params.group_, journal_params.name_);
}
Zeder::Flavour GetZederInstanceForGroup(const Config::GroupParams &group_params) {
return GetZederInstanceFromGroupName(group_params.name_);
}
Zeder::Flavour GetZederInstanceFromMarcRecord(const MARC::Record &record) {
const auto zid_b(record.getFirstSubfieldValue("ZID", 'b'));
if (zid_b == "ixtheo")
return Zeder::Flavour::IXTHEO;
else if (zid_b == "krimdok")
return Zeder::Flavour::KRIMDOK;
throw std::runtime_error("missing ZID system field in Zotero record '" + record.getControlNumber() + "'");
}
} // end namespace ZederInterop
} // end namespace ZoteroHarvester
<commit_msg>Appropriately handle non-existing field<commit_after>/** \brief Classes related to the Zotero Harvester's interoperation with the Zeder database
* \author Madeeswaran Kannan
*
* \copyright 2020-2021 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ZoteroHarvesterZederInterop.h"
#include <cmath>
#include "util.h"
namespace ZoteroHarvester {
namespace ZederInterop {
const std::map<Config::JournalParams::IniKey, std::string> INI_KEY_TO_ZEDER_COLUMN_MAP {
{ Config::JournalParams::IniKey::NAME, "tit" },
{ Config::JournalParams::IniKey::ONLINE_PPN, "eppn" },
{ Config::JournalParams::IniKey::PRINT_PPN, "pppn" },
{ Config::JournalParams::IniKey::ONLINE_ISSN, "essn" },
{ Config::JournalParams::IniKey::PRINT_ISSN, "issn" },
{ Config::JournalParams::IniKey::EXPECTED_LANGUAGES, "sprz" },
{ Config::JournalParams::IniKey::SSGN, "ber" },
{ Config::JournalParams::IniKey::LICENSE, "oacc" },
{ Config::JournalParams::IniKey::PERSONALIZED_AUTHORS, "tiefp"},
// The following two columns/INI keys are intentionally excluded as they are special cases.
// Even though there is a one-to-one correspondence for each to the two columns,
// they are stored differently in memory (in the Zeder::Entry class) than all other
// columns. Therefore, they can't be trivially mapped to each other.
// { Config::JournalParams::IniKey::ZEDER_ID, "Z" },
// { Config::JournalParams::IniKey::ZEDER_MODIFIED_TIME, "Mtime" },
};
static std::string ResolveGroup(const Zeder::Entry &/*unused*/, const Zeder::Flavour zeder_flavour) {
return Zeder::FLAVOUR_TO_STRING_MAP.at(zeder_flavour);
}
static std::string ResolveEntryPointURL(const Zeder::Entry &zeder_entry, const Zeder::Flavour zeder_flavour) {
const auto &rss(zeder_entry.getAttribute("rss", ""));
const auto &p_zot2(zeder_entry.getAttribute("p_zot2", ""));
const auto &url1(zeder_entry.getAttribute("url1", ""));
const auto &url2(zeder_entry.getAttribute("url2", ""));
// Field priorities differ between IxTheo and KrimDok (based on who updated which field first)
switch (zeder_flavour) {
case Zeder::Flavour::IXTHEO:
if (not rss.empty())
return rss;
else if (not p_zot2.empty())
return p_zot2;
else if (not url2.empty())
return url2;
else
return url1;
case Zeder::Flavour::KRIMDOK:
if (not rss.empty())
return rss;
else if (not url2.empty())
return url2;
else if (not p_zot2.empty())
return p_zot2;
else
return url1;
default:
return "";
}
}
static std::string ResolveHarvesterOperation(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
const auto &z_type(zeder_entry.getAttribute("z_type", ""));
if (z_type == "rss")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::RSS);
else if (z_type == "crawl")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::CRAWL);
else if (z_type == "email")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::EMAIL);
else if (z_type == "api")
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::APIQUERY);
else if (z_type == "") { /* Fall back to old approach if not set */
const auto &rss(zeder_entry.getAttribute("rss", ""));
if (not rss.empty())
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::RSS);
else
return Config::HARVESTER_OPERATION_TO_STRING_MAP.at(Config::HarvesterOperation::CRAWL);
} else
LOG_ERROR("Invalid Harvester operation value \"" + z_type + "\" for in field z_type");
}
std::string ResolveUploadOperation(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
if (zeder_entry.getAttribute("prodf", "") == "zota")
return Config::UPLOAD_OPERATION_TO_STRING_MAP.at(Config::UploadOperation::LIVE);
const std::string prode(zeder_entry.getAttribute("prode", ""));
if (prode == "zotat" or prode == "zota")
return Config::UPLOAD_OPERATION_TO_STRING_MAP.at(Config::UploadOperation::TEST);
return Config::UPLOAD_OPERATION_TO_STRING_MAP.at(Config::UploadOperation::NONE);
}
static std::string ResolveUpdateWindow(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
// Calculate an admissible range in days for a frequency given per year.
// Right now we simply ignore entries that cannot be suitably converted to float.
float frequency_as_float;
if (not StringUtil::ToFloat(zeder_entry.getAttribute("freq", ""), &frequency_as_float))
return "";
float admissible_range = (365 / frequency_as_float) * 1.5;
return std::to_string(static_cast<int>(std::round(admissible_range)));
}
static std::string ResolveSelectiveEvaluation(const Zeder::Entry &zeder_entry, const Zeder::Flavour /*unused*/) {
if (zeder_entry.getAttribute("ausw", "") == "selek")
return "true";
else
return "false";
}
const std::map<Config::JournalParams::IniKey, std::function<std::string(const Zeder::Entry &, const Zeder::Flavour)>> INI_KEY_TO_ZEDER_RESOLVER_MAP {
{ Config::JournalParams::IniKey::GROUP, ResolveGroup },
{ Config::JournalParams::IniKey::ENTRY_POINT_URL, ResolveEntryPointURL },
{ Config::JournalParams::IniKey::HARVESTER_OPERATION, ResolveHarvesterOperation },
{ Config::JournalParams::IniKey::UPLOAD_OPERATION, ResolveUploadOperation },
{ Config::JournalParams::IniKey::UPDATE_WINDOW, ResolveUpdateWindow },
{ Config::JournalParams::IniKey::SELECTIVE_EVALUATION, ResolveSelectiveEvaluation },
};
static inline bool IsValidZederValue(const std::string &zeder_value) {
return zeder_value != "NV";
}
std::string GetJournalParamsIniValueFromZederEntry(const Zeder::Entry &zeder_entry, const Zeder::Flavour zeder_flavour,
const Config::JournalParams::IniKey ini_key)
{
std::string zeder_value;
if (INI_KEY_TO_ZEDER_COLUMN_MAP.find(ini_key) != INI_KEY_TO_ZEDER_COLUMN_MAP.end())
zeder_value = zeder_entry.getAttribute(INI_KEY_TO_ZEDER_COLUMN_MAP.at(ini_key), "");
else if (INI_KEY_TO_ZEDER_RESOLVER_MAP.find(ini_key) != INI_KEY_TO_ZEDER_RESOLVER_MAP.end())
zeder_value = INI_KEY_TO_ZEDER_RESOLVER_MAP.at(ini_key)(zeder_entry, zeder_flavour);
else
LOG_ERROR("unable to resolve value from Zeder entry for INI key '" + Config::JournalParams::GetIniKeyString(ini_key) + "'");
zeder_value = TextUtil::CollapseAndTrimWhitespace(zeder_value);
if (IsValidZederValue(zeder_value))
return zeder_value;
else
return "";
}
static Zeder::Flavour GetZederInstanceFromGroupName(const std::string &group_name, const std::string &journal_name = "") {
if (::strcasecmp(group_name.c_str(), "ixtheo") == 0)
return Zeder::Flavour::IXTHEO;
else if (::strcasecmp(group_name.c_str(), "relbib") == 0)
return Zeder::Flavour::IXTHEO;
else if (::strcasecmp(group_name.c_str(), "krimdok") == 0)
return Zeder::Flavour::KRIMDOK;
if (not journal_name.empty())
LOG_ERROR("group '" + group_name + "' for journal '" + journal_name + "' could not be assigned to either Zeder instance");
else
LOG_ERROR("group '" + group_name + "' could not be assigned to either Zeder instance");
}
Zeder::Flavour GetZederInstanceForJournal(const Config::JournalParams &journal_params) {
return GetZederInstanceFromGroupName(journal_params.group_, journal_params.name_);
}
Zeder::Flavour GetZederInstanceForGroup(const Config::GroupParams &group_params) {
return GetZederInstanceFromGroupName(group_params.name_);
}
Zeder::Flavour GetZederInstanceFromMarcRecord(const MARC::Record &record) {
const auto zid_b(record.getFirstSubfieldValue("ZID", 'b'));
if (zid_b == "ixtheo")
return Zeder::Flavour::IXTHEO;
else if (zid_b == "krimdok")
return Zeder::Flavour::KRIMDOK;
throw std::runtime_error("missing ZID system field in Zotero record '" + record.getControlNumber() + "'");
}
} // end namespace ZederInterop
} // end namespace ZoteroHarvester
<|endoftext|>
|
<commit_before>#ifndef DIRICHLET_SHETXCOC
#define DIRICHLET_SHETXCOC
namespace Dune {
namespace Functionals {
namespace Constraints {
/** @brief Constraints for Dirichlet values on the entire boundary domain
*
* This class implements constraints on the degrees of freedom on a @ref
* Subspace::Linear "linear subspace" @endref.
*
* @tparam DiscFuncSpace
*/
template <class DiscFuncSpace>
class Dirichlet
{
public:
typedef DiscFuncSpace DiscreteFunctionSpace;
typedef typename DiscreteFunctionSpace::GridPartType GridPartType;
static const int griddim = GridPartType::GridType::dimension;
typedef Constraints::LocalDefault<double, griddim, griddim> LocalConstraintsType;
public:
template <class DomainConstraint>
Dirichlet(DiscFuncSpace& space, DomainConstraint& domainConstraint)
: space_(space)
, gridPart_(space.gridPart())
{
}
template <class Entity>
const LocalConstraintsType local(const Entity& en)
{
typedef typename DiscFuncSpace::BaseFunctionSet BFS;
const BFS& bfs = space_.baseFunctionSet(en);
const int numCols = bfs.numBaseFunctions();
LocalConstraintsType lc(numCols);
typedef typename DFS::Iterator ItType;
typedef typename Entity::LeafIntersectionIterator IntersectionIterator;
typedef typename IntersectionIterator::Intersection Intersection;
int numRows = 0;
ItType it = space_.begin();
for (; it != space_.end(); it++) {
const Entity& en = *it;
IntersectionIterator iit = en.ileafbegin();
for (; iit != en.ileafend(); iit++) {
const Intersection& ii = *iit;
if (ii.boundary()) {
lc.setRowDofs(numRows, space_.mapToGlobal(en, numRows));
for (unsigned int i = 0; i < numCols; i++) {
lc.setColumnDofs(i, space_.mapToGlobal(en, i));
lc.setLocalMatrix(numRows, i) = 0;
}
lc.setLocalMatrix(numRows, numRows) = 1;
++numRows;
}
}
}
lc.setRowDofsSize(numRows);
return lc;
}
private:
DiscreteFunctionSpace& space_;
GridPartType& gridPart_;
}; // end class Dirichlet
} // end of namespace Constraints
} // end of namespace Functionals
} // end of namespace Dune
#endif /* end of include guard: DIRICHLET_SHETXCOC */
<commit_msg>temporary commit documentation in dirichlet constraints<commit_after>#ifndef DIRICHLET_SHETXCOC
#define DIRICHLET_SHETXCOC
namespace Dune {
namespace Functionals {
namespace Constraints {
/** @brief Constraints for Dirichlet values on the entire boundary domain
*
* This class implements constraints on the degrees of freedom on a @ref
* Subspace::Linear "linear subspace" @endref.
*
* Constraints efficiently implement functionals @f$ f_i:\cal X_H \to
* \mathbb{R}@f$ for each degree of freedom @f$i\in C \subset
* \{1,\dots,H\}@f$, where $H$ is the number of degree of freedoms in the
* underlying discrete function space @f$\cal X_H\@f$. In case of this Dirichlet constraints class, the set
* @f$\{1,\dots,C\}@f$ includes all
*
* @note The Dirichlet constraints only make sense on a finite element space,
* not on a discontinuous discrete function space.
*
* @tparam DiscFuncSpace discrete function space on which constraints shall
* be applied.
*/
template <class DiscFuncSpace>
class Dirichlet
{
public:
//! Discrete function space on which the Dirichlet constraints are applied
typedef DiscFuncSpace DiscreteFunctionSpace;
//! Underlying grid part
typedef typename DiscreteFunctionSpace::GridPartType GridPartType;
//! Dimension of the grid part
static const int griddim = GridPartType::GridType::dimension;
//! Return type of local() method, implementing the LocalConstraints
//! interface
typedef Constraints::LocalDefault<double, griddim, griddim> LocalConstraintsType;
public:
/** Constructor for the Dirichlet constraints
*
* @param space discrete function space object on which the Dirichlet
* constraints are applied
*/
Dirichlet(DiscFuncSpace& space)
: space_(space)
, gridPart_(space.gridPart())
{
}
/** return a local constraint object for the entity \a en
*
* @param en Entity for which the local constraints shall be compted
*
* @returns local constraints object (copyable).
*/
template <class Entity>
const LocalConstraintsType local(const Entity& en)
{
typedef typename DiscFuncSpace::BaseFunctionSet BFS;
const BFS& bfs = space_.baseFunctionSet(en);
const int numCols = bfs.numBaseFunctions();
LocalConstraintsType lc(numCols);
typedef typename DFS::Iterator ItType;
typedef typename Entity::LeafIntersectionIterator IntersectionIterator;
typedef typename IntersectionIterator::Intersection Intersection;
int numRows = 0;
ItType it = space_.begin();
for (; it != space_.end(); it++) {
const Entity& en = *it;
IntersectionIterator iit = en.ileafbegin();
for (; iit != en.ileafend(); iit++) {
const Intersection& ii = *iit;
if (ii.boundary()) {
lc.setRowDofs(numRows, space_.mapToGlobal(en, numRows));
for (unsigned int i = 0; i < numCols; i++) {
lc.setColumnDofs(i, space_.mapToGlobal(en, i));
lc.setLocalMatrix(numRows, i) = 0;
}
lc.setLocalMatrix(numRows, numRows) = 1;
++numRows;
}
}
}
lc.setRowDofsSize(numRows);
return lc;
}
private:
DiscreteFunctionSpace& space_;
GridPartType& gridPart_;
}; // end class Dirichlet
} // end of namespace Constraints
} // end of namespace Functionals
} // end of namespace Dune
#endif /* end of include guard: DIRICHLET_SHETXCOC */
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 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 "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <objidl.h>
#include <mlang.h>
#endif
#include "chrome/renderer/render_process.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/histogram.h"
#include "base/path_service.h"
#include "base/sys_info.h"
// TODO(jar): DNS calls should be renderer specific, not including browser.
#include "chrome/browser/net/dns_global.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/transport_dib.h"
#include "chrome/renderer/render_view.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_message_utils.h"
#include "media/base/media.h"
#include "webkit/glue/webkit_glue.h"
static size_t GetMaxSharedMemorySize() {
static int size = 0;
#if defined(OS_LINUX)
if (size == 0) {
std::string contents;
file_util::ReadFileToString(FilePath("/proc/sys/kernel/shmmax"), &contents);
size = strtoul(contents.c_str(), NULL, 0);
}
#endif
return size;
}
//-----------------------------------------------------------------------------
RenderProcess::RenderProcess()
: ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_(
base::TimeDelta::FromSeconds(5),
this, &RenderProcess::ClearTransportDIBCache)),
sequence_number_(0) {
in_process_plugins_ = InProcessPlugins();
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i)
shared_mem_cache_[i] = NULL;
#if defined(OS_WIN)
// HACK: See http://b/issue?id=1024307 for rationale.
if (GetModuleHandle(L"LPK.DLL") == NULL) {
// Makes sure lpk.dll is loaded by gdi32 to make sure ExtTextOut() works
// when buffering into a EMF buffer for printing.
typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs);
GdiInitializeLanguagePack gdi_init_lpk =
reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress(
GetModuleHandle(L"GDI32.DLL"),
"GdiInitializeLanguagePack"));
DCHECK(gdi_init_lpk);
if (gdi_init_lpk) {
gdi_init_lpk(0);
}
}
#endif
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kJavaScriptFlags)) {
webkit_glue::SetJavaScriptFlags(
command_line.GetSwitchValue(switches::kJavaScriptFlags));
}
// Out of process dev tools rely upon auto break behavior.
webkit_glue::SetJavaScriptFlags(
L"--debugger-auto-break"
// Enable lazy in-memory profiling.
L" --prof --prof-lazy --logfile=* --compress-log");
if (command_line.HasSwitch(switches::kEnableWatchdog)) {
// TODO(JAR): Need to implement renderer IO msgloop watchdog.
}
if (command_line.HasSwitch(switches::kDumpHistogramsOnExit)) {
StatisticsRecorder::set_dump_on_exit(true);
}
FilePath module_path;
initialized_media_library_ =
PathService::Get(base::DIR_MODULE, &module_path) &&
media::InitializeMediaLibrary(module_path);
}
RenderProcess::~RenderProcess() {
// TODO(port)
// Try and limit what we pull in for our non-Win unit test bundle
#ifndef NDEBUG
// log important leaked objects
webkit_glue::CheckForLeaks();
#endif
GetShutDownEvent()->Signal();
ClearTransportDIBCache();
}
bool RenderProcess::InProcessPlugins() {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
#if defined(OS_LINUX)
// Plugin processes require a UI message loop, and the Linux message loop
// implementation only allows one UI loop per process.
if (command_line.HasSwitch(switches::kInProcessPlugins))
NOTIMPLEMENTED() << ": in process plugins not supported on Linux";
return command_line.HasSwitch(switches::kInProcessPlugins);
#else
return command_line.HasSwitch(switches::kInProcessPlugins) ||
command_line.HasSwitch(switches::kSingleProcess);
#endif
}
// -----------------------------------------------------------------------------
// Platform specific code for dealing with bitmap transport...
TransportDIB* RenderProcess::CreateTransportDIB(size_t size) {
#if defined(OS_WIN) || defined(OS_LINUX)
// Windows and Linux create transport DIBs inside the renderer
return TransportDIB::Create(size, sequence_number_++);
#elif defined(OS_MACOSX) // defined(OS_WIN) || defined(OS_LINUX)
// Mac creates transport DIBs in the browser, so we need to do a sync IPC to
// get one.
TransportDIB::Handle handle;
IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(size, &handle);
if (!main_thread()->Send(msg))
return NULL;
if (handle.fd < 0)
return NULL;
return TransportDIB::Map(handle);
#endif // defined(OS_MACOSX)
}
void RenderProcess::FreeTransportDIB(TransportDIB* dib) {
if (!dib)
return;
#if defined(OS_MACOSX)
// On Mac we need to tell the browser that it can drop a reference to the
// shared memory.
IPC::Message* msg = new ViewHostMsg_FreeTransportDIB(dib->id());
main_thread()->Send(msg);
#endif
delete dib;
}
// -----------------------------------------------------------------------------
skia::PlatformCanvas* RenderProcess::GetDrawingCanvas(
TransportDIB** memory, const gfx::Rect& rect) {
int width = rect.width();
int height = rect.height();
const size_t stride = skia::PlatformCanvas::StrideForWidth(rect.width());
const size_t max_size = GetMaxSharedMemorySize();
// If the requested size is too big, reduce the height. Ideally we might like
// to reduce the width as well to make the size reduction more "balanced", but
// it rarely comes up in practice.
if ((max_size != 0) && (height * stride > max_size))
height = max_size / stride;
const size_t size = height * stride;
if (!GetTransportDIBFromCache(memory, size)) {
*memory = CreateTransportDIB(size);
if (!*memory)
return false;
}
return (*memory)->GetPlatformCanvas(width, height);
}
void RenderProcess::ReleaseTransportDIB(TransportDIB* mem) {
if (PutSharedMemInCache(mem)) {
shared_mem_cache_cleaner_.Reset();
return;
}
FreeTransportDIB(mem);
}
bool RenderProcess::GetTransportDIBFromCache(TransportDIB** mem,
size_t size) {
// look for a cached object that is suitable for the requested size.
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) {
if (shared_mem_cache_[i] &&
size <= shared_mem_cache_[i]->size()) {
*mem = shared_mem_cache_[i];
shared_mem_cache_[i] = NULL;
return true;
}
}
return false;
}
int RenderProcess::FindFreeCacheSlot(size_t size) {
// simple algorithm:
// - look for an empty slot to store mem, or
// - if full, then replace smallest entry which is smaller than |size|
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) {
if (shared_mem_cache_[i] == NULL)
return i;
}
size_t smallest_size = size;
int smallest_index = -1;
for (size_t i = 1; i < arraysize(shared_mem_cache_); ++i) {
const size_t entry_size = shared_mem_cache_[i]->size();
if (entry_size < smallest_size) {
smallest_size = entry_size;
smallest_index = i;
}
}
if (smallest_index != -1) {
FreeTransportDIB(shared_mem_cache_[smallest_index]);
shared_mem_cache_[smallest_index] = NULL;
}
return smallest_index;
}
bool RenderProcess::PutSharedMemInCache(TransportDIB* mem) {
const int slot = FindFreeCacheSlot(mem->size());
if (slot == -1)
return false;
shared_mem_cache_[slot] = mem;
return true;
}
void RenderProcess::ClearTransportDIBCache() {
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) {
if (shared_mem_cache_[i]) {
FreeTransportDIB(shared_mem_cache_[i]);
shared_mem_cache_[i] = NULL;
}
}
}
<commit_msg>DevTools: Change js flags apply order: first ours, then from command line.<commit_after>// Copyright (c) 2006-2008 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 "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <objidl.h>
#include <mlang.h>
#endif
#include "chrome/renderer/render_process.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/histogram.h"
#include "base/path_service.h"
#include "base/sys_info.h"
// TODO(jar): DNS calls should be renderer specific, not including browser.
#include "chrome/browser/net/dns_global.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/transport_dib.h"
#include "chrome/renderer/render_view.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_message_utils.h"
#include "media/base/media.h"
#include "webkit/glue/webkit_glue.h"
static size_t GetMaxSharedMemorySize() {
static int size = 0;
#if defined(OS_LINUX)
if (size == 0) {
std::string contents;
file_util::ReadFileToString(FilePath("/proc/sys/kernel/shmmax"), &contents);
size = strtoul(contents.c_str(), NULL, 0);
}
#endif
return size;
}
//-----------------------------------------------------------------------------
RenderProcess::RenderProcess()
: ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_(
base::TimeDelta::FromSeconds(5),
this, &RenderProcess::ClearTransportDIBCache)),
sequence_number_(0) {
in_process_plugins_ = InProcessPlugins();
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i)
shared_mem_cache_[i] = NULL;
#if defined(OS_WIN)
// HACK: See http://b/issue?id=1024307 for rationale.
if (GetModuleHandle(L"LPK.DLL") == NULL) {
// Makes sure lpk.dll is loaded by gdi32 to make sure ExtTextOut() works
// when buffering into a EMF buffer for printing.
typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs);
GdiInitializeLanguagePack gdi_init_lpk =
reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress(
GetModuleHandle(L"GDI32.DLL"),
"GdiInitializeLanguagePack"));
DCHECK(gdi_init_lpk);
if (gdi_init_lpk) {
gdi_init_lpk(0);
}
}
#endif
// Out of process dev tools rely upon auto break behavior.
webkit_glue::SetJavaScriptFlags(
L"--debugger-auto-break"
// Enable lazy in-memory profiling.
L" --prof --prof-lazy --logfile=* --compress-log");
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kJavaScriptFlags)) {
webkit_glue::SetJavaScriptFlags(
command_line.GetSwitchValue(switches::kJavaScriptFlags));
}
if (command_line.HasSwitch(switches::kEnableWatchdog)) {
// TODO(JAR): Need to implement renderer IO msgloop watchdog.
}
if (command_line.HasSwitch(switches::kDumpHistogramsOnExit)) {
StatisticsRecorder::set_dump_on_exit(true);
}
FilePath module_path;
initialized_media_library_ =
PathService::Get(base::DIR_MODULE, &module_path) &&
media::InitializeMediaLibrary(module_path);
}
RenderProcess::~RenderProcess() {
// TODO(port)
// Try and limit what we pull in for our non-Win unit test bundle
#ifndef NDEBUG
// log important leaked objects
webkit_glue::CheckForLeaks();
#endif
GetShutDownEvent()->Signal();
ClearTransportDIBCache();
}
bool RenderProcess::InProcessPlugins() {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
#if defined(OS_LINUX)
// Plugin processes require a UI message loop, and the Linux message loop
// implementation only allows one UI loop per process.
if (command_line.HasSwitch(switches::kInProcessPlugins))
NOTIMPLEMENTED() << ": in process plugins not supported on Linux";
return command_line.HasSwitch(switches::kInProcessPlugins);
#else
return command_line.HasSwitch(switches::kInProcessPlugins) ||
command_line.HasSwitch(switches::kSingleProcess);
#endif
}
// -----------------------------------------------------------------------------
// Platform specific code for dealing with bitmap transport...
TransportDIB* RenderProcess::CreateTransportDIB(size_t size) {
#if defined(OS_WIN) || defined(OS_LINUX)
// Windows and Linux create transport DIBs inside the renderer
return TransportDIB::Create(size, sequence_number_++);
#elif defined(OS_MACOSX) // defined(OS_WIN) || defined(OS_LINUX)
// Mac creates transport DIBs in the browser, so we need to do a sync IPC to
// get one.
TransportDIB::Handle handle;
IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(size, &handle);
if (!main_thread()->Send(msg))
return NULL;
if (handle.fd < 0)
return NULL;
return TransportDIB::Map(handle);
#endif // defined(OS_MACOSX)
}
void RenderProcess::FreeTransportDIB(TransportDIB* dib) {
if (!dib)
return;
#if defined(OS_MACOSX)
// On Mac we need to tell the browser that it can drop a reference to the
// shared memory.
IPC::Message* msg = new ViewHostMsg_FreeTransportDIB(dib->id());
main_thread()->Send(msg);
#endif
delete dib;
}
// -----------------------------------------------------------------------------
skia::PlatformCanvas* RenderProcess::GetDrawingCanvas(
TransportDIB** memory, const gfx::Rect& rect) {
int width = rect.width();
int height = rect.height();
const size_t stride = skia::PlatformCanvas::StrideForWidth(rect.width());
const size_t max_size = GetMaxSharedMemorySize();
// If the requested size is too big, reduce the height. Ideally we might like
// to reduce the width as well to make the size reduction more "balanced", but
// it rarely comes up in practice.
if ((max_size != 0) && (height * stride > max_size))
height = max_size / stride;
const size_t size = height * stride;
if (!GetTransportDIBFromCache(memory, size)) {
*memory = CreateTransportDIB(size);
if (!*memory)
return false;
}
return (*memory)->GetPlatformCanvas(width, height);
}
void RenderProcess::ReleaseTransportDIB(TransportDIB* mem) {
if (PutSharedMemInCache(mem)) {
shared_mem_cache_cleaner_.Reset();
return;
}
FreeTransportDIB(mem);
}
bool RenderProcess::GetTransportDIBFromCache(TransportDIB** mem,
size_t size) {
// look for a cached object that is suitable for the requested size.
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) {
if (shared_mem_cache_[i] &&
size <= shared_mem_cache_[i]->size()) {
*mem = shared_mem_cache_[i];
shared_mem_cache_[i] = NULL;
return true;
}
}
return false;
}
int RenderProcess::FindFreeCacheSlot(size_t size) {
// simple algorithm:
// - look for an empty slot to store mem, or
// - if full, then replace smallest entry which is smaller than |size|
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) {
if (shared_mem_cache_[i] == NULL)
return i;
}
size_t smallest_size = size;
int smallest_index = -1;
for (size_t i = 1; i < arraysize(shared_mem_cache_); ++i) {
const size_t entry_size = shared_mem_cache_[i]->size();
if (entry_size < smallest_size) {
smallest_size = entry_size;
smallest_index = i;
}
}
if (smallest_index != -1) {
FreeTransportDIB(shared_mem_cache_[smallest_index]);
shared_mem_cache_[smallest_index] = NULL;
}
return smallest_index;
}
bool RenderProcess::PutSharedMemInCache(TransportDIB* mem) {
const int slot = FindFreeCacheSlot(mem->size());
if (slot == -1)
return false;
shared_mem_cache_[slot] = mem;
return true;
}
void RenderProcess::ClearTransportDIBCache() {
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) {
if (shared_mem_cache_[i]) {
FreeTransportDIB(shared_mem_cache_[i]);
shared_mem_cache_[i] = NULL;
}
}
}
<|endoftext|>
|
<commit_before>#ifndef __CALLBACK_ENGINE_HPP_INCLUDED
#define __CALLBACK_ENGINE_HPP_INCLUDED
#include "cpp/ylikuutio/common/any_value.hpp"
// Include standard headers
#include <queue> // std::queue
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <unordered_map> // std::unordered_map
#include <vector> // std::vector
namespace model
{
class World;
}
// callback typedefs in alphabetical order.
typedef bool (*BoolToBoolCallback)(bool);
typedef float (*BoolToFloatCallback)(bool);
typedef int (*BoolToIntCallback)(bool);
typedef void (*BoolToVoidCallback)(bool);
typedef bool (*FloatToBoolCallback)(float);
typedef float (*FloatToFloatCallback)(float);
typedef int (*FloatToIntCallback)(float);
typedef void (*FloatToVoidCallback)(float);
typedef bool (*IntToBoolCallback)(int);
typedef float (*IntToFloatCallback)(int);
typedef int (*IntToIntCallback)(int);
typedef void (*IntToVoidCallback)(int);
typedef bool (*VoidToBoolCallback)(void);
typedef float (*VoidToFloatCallback)(void);
typedef int (*VoidToIntCallback)(void);
typedef void (*VoidToVoidCallback)(void);
typedef void (*WorldToVoidCallback)(model::World*);
typedef void (*AnyValueToVoidCallback)(AnyValue);
typedef AnyValue (*VoidToAnyValueCallback)(void);
typedef AnyValue (*AnyValueToAnyValueCallback)(AnyValue);
namespace callback_system
{
class CallbackObject;
class CallbackEngine
{
// `CallbackEngine` is an object that contains some callbacks and hashmaps that are used for input and output parameters.
// `CallbackEngine` provides a way to create callback chains.
//
// How to use.
// 1. Create a new `CallbackEngine`. No callbacks have been
// defined yet. Calling `CallbackEngine.execute()` at this
// point will simply go through an empty vector and
// practically won't do anything interesting.
// 2. Create a new `CallbackObject`, give pointer to the
// recently created `CallbackEngine` as input parameter.
// 3. If the callback has parameter[s], create a new
// `CallbackParameter` for each parameter, give `CallbackObject`
// as input parameter for the `CallbackParameter` constructor.
public:
// constructor.
CallbackEngine();
// destructor.
~CallbackEngine();
// this method sets a callback object pointer.
void set_callback_object_pointer(uint32_t childID, void* parent_pointer);
// getter functions for callbacks and callback objects.
bool get_bool(std::string name);
float get_float(std::string name);
double get_double(std::string name);
int32_t get_int32_t(std::string name);
uint32_t get_uint32_t(std::string name);
void* get_void_pointer(std::string name);
// setter functions for callbacks and callback objects.
void set_bool(std::string name, bool value);
void set_float(std::string name, float value);
void set_double(std::string name, double value);
void set_int32_t(std::string name, int32_t value);
void set_uint32_t(std::string name, uint32_t value);
void set_void_pointer(std::string name, void* value);
void set_world_pointer(std::string name, model::World* value);
// execute all callbacks.
AnyValue execute();
private:
std::vector<void*> callback_object_pointer_vector;
std::queue<uint32_t> free_callback_objectID_queue;
std::unordered_map<std::string, AnyValue> anyvalue_hashmap;
};
}
#endif
<commit_msg>Poistettu ylimääräisiä takaisinkutsu-typedef-määrityksiä.<commit_after>#ifndef __CALLBACK_ENGINE_HPP_INCLUDED
#define __CALLBACK_ENGINE_HPP_INCLUDED
#include "cpp/ylikuutio/common/any_value.hpp"
// Include standard headers
#include <queue> // std::queue
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <unordered_map> // std::unordered_map
#include <vector> // std::vector
namespace model
{
class World;
}
// callback typedefs in alphabetical order.
typedef void (*VoidToVoidCallback)(void);
typedef void (*AnyValueToVoidCallback)(AnyValue);
typedef AnyValue (*VoidToAnyValueCallback)(void);
typedef AnyValue (*AnyValueToAnyValueCallback)(AnyValue);
namespace callback_system
{
class CallbackObject;
class CallbackEngine
{
// `CallbackEngine` is an object that contains some callbacks and hashmaps that are used for input and output parameters.
// `CallbackEngine` provides a way to create callback chains.
//
// How to use.
// 1. Create a new `CallbackEngine`. No callbacks have been
// defined yet. Calling `CallbackEngine.execute()` at this
// point will simply go through an empty vector and
// practically won't do anything interesting.
// 2. Create a new `CallbackObject`, give pointer to the
// recently created `CallbackEngine` as input parameter.
// 3. If the callback has parameter[s], create a new
// `CallbackParameter` for each parameter, give `CallbackObject`
// as input parameter for the `CallbackParameter` constructor.
public:
// constructor.
CallbackEngine();
// destructor.
~CallbackEngine();
// this method sets a callback object pointer.
void set_callback_object_pointer(uint32_t childID, void* parent_pointer);
// getter functions for callbacks and callback objects.
bool get_bool(std::string name);
float get_float(std::string name);
double get_double(std::string name);
int32_t get_int32_t(std::string name);
uint32_t get_uint32_t(std::string name);
void* get_void_pointer(std::string name);
// setter functions for callbacks and callback objects.
void set_bool(std::string name, bool value);
void set_float(std::string name, float value);
void set_double(std::string name, double value);
void set_int32_t(std::string name, int32_t value);
void set_uint32_t(std::string name, uint32_t value);
void set_void_pointer(std::string name, void* value);
void set_world_pointer(std::string name, model::World* value);
// execute all callbacks.
AnyValue execute();
private:
std::vector<void*> callback_object_pointer_vector;
std::queue<uint32_t> free_callback_objectID_queue;
std::unordered_map<std::string, AnyValue> anyvalue_hashmap;
};
}
#endif
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\ProjectEuler\Problem1.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ProjectEulerTests
{
TEST_CLASS(Problem1Tests)
{
public:
TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(0);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(1);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(2);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(3);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3)
{
auto result = Problem1::SumMultiplesOf3And5Below(4);
Assert::AreEqual(3, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3)
{
auto result = Problem1::SumMultiplesOf3And5Below(5);
Assert::AreEqual(3, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8)
{
auto result = Problem1::SumMultiplesOf3And5Below(6);
Assert::AreEqual(8, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14)
{
auto result = Problem1::SumMultiplesOf3And5Below(7);
Assert::AreEqual(14, result);
}
};
}<commit_msg>green-commit - SumMultiplesOf3And5Below_Input8_Returns14, SumMultiplesOf3And5Below_Input9_Returns14, SumMultiplesOf3And5Below_Input10_Returns23, SumMultiplesOf3And5Below_Input100_Returns2318, SumMultiplesOf3And5Below_Input1000_Returns233168, SumMultiplesOf3And5Below_Input10000_Returns23331668<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\ProjectEuler\Problem1.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ProjectEulerTests
{
TEST_CLASS(Problem1Tests)
{
public:
TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(0);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(1);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(2);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0)
{
auto result = Problem1::SumMultiplesOf3And5Below(3);
Assert::AreEqual(0, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3)
{
auto result = Problem1::SumMultiplesOf3And5Below(4);
Assert::AreEqual(3, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3)
{
auto result = Problem1::SumMultiplesOf3And5Below(5);
Assert::AreEqual(3, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8)
{
auto result = Problem1::SumMultiplesOf3And5Below(6);
Assert::AreEqual(8, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14)
{
auto result = Problem1::SumMultiplesOf3And5Below(7);
Assert::AreEqual(14, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14)
{
auto result = Problem1::SumMultiplesOf3And5Below(8);
Assert::AreEqual(14, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14)
{
auto result = Problem1::SumMultiplesOf3And5Below(9);
Assert::AreEqual(14, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23)
{
auto result = Problem1::SumMultiplesOf3And5Below(10);
Assert::AreEqual(23, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318)
{
auto result = Problem1::SumMultiplesOf3And5Below(100);
Assert::AreEqual(2318, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168)
{
auto result = Problem1::SumMultiplesOf3And5Below(1000);
Assert::AreEqual(233168, result);
}
TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668)
{
auto result = Problem1::SumMultiplesOf3And5Below(10000);
Assert::AreEqual(23331668, result);
}
};
}<|endoftext|>
|
<commit_before>#include "maps.h"
namespace gsnizk {
G1 B1::extract(const CRS &crs) const {
return _2 - (Fp(1) / crs.j1) * _1;
}
G2 B2::extract(const CRS &crs) const {
return _2 - (Fp(1) / crs.j2) * _1;
}
GT BT::extract(const CRS &crs) const {
Fp p = Fp(-1) / crs.j1;
return (_22 * (_12 ^ p)) * ((_21 * (_11 ^ p)) ^ (Fp(-1) / crs.j2));
}
BT BT::pairing(const B1 &a, const B2 &b) {
// TODO precompute pairings?
return BT(GT::pairing(a._1, b._1), GT::pairing(a._1, b._2),
GT::pairing(a._2, b._1), GT::pairing(a._2, b._2));
}
BT BT::pairing(const std::vector<std::pair<B1, B2> > &lst) {
// TODO precompute pairings?
std::vector<std::pair<G1, G2> > p11, p12, p21, p22;
p11.reserve(lst.size());
p12.reserve(lst.size());
p21.reserve(lst.size());
p22.reserve(lst.size());
for (const std::pair<B1, B2> p: lst) {
p11.push_back(std::pair<G1, G2>(p.first._1, p.second._1));
p12.push_back(std::pair<G1, G2>(p.first._1, p.second._2));
p21.push_back(std::pair<G1, G2>(p.first._2, p.second._1));
p22.push_back(std::pair<G1, G2>(p.first._2, p.second._2));
}
return BT(GT::pairing(p11), GT::pairing(p12),
GT::pairing(p21), GT::pairing(p22));
}
CRS::CRS(bool binding) : v1(G1(), G1::getRand()), v2(G2(), G2::getRand()),
type(binding ? CRS_TYPE_EXTRACT : CRS_TYPE_ZK),
i1(Fp::getRand()), j1(Fp::getRand()),
i2(Fp::getRand()), j2(Fp::getRand())
{
computeElements();
}
void CRS::makePublic() {
if (type != CRS_TYPE_PUBLIC) {
i1 = Fp();
i2 = Fp();
type = CRS_TYPE_PUBLIC;
}
}
std::ostream &operator<<(std::ostream &stream, const CRS &crs) {
stream << crs.type;
if (crs.type == CRS_TYPE_PUBLIC) {
stream << crs.u1 << crs.v1 << crs.w1;
stream << crs.u2 << crs.v2 << crs.w2;
} else {
stream << crs.v1._2 << crs.v2._2;
stream << crs.i1 << crs.j1 << crs.i2 << crs.j2;
}
return stream;
}
std::istream &operator>>(std::istream &stream, CRS &crs) {
stream >> crs.type;
// TODO precomputations?
if (crs.type == CRS_TYPE_PUBLIC) {
stream >> crs.u1 >> crs.v1 >> crs.w1;
stream >> crs.u2 >> crs.v2 >> crs.w2;
#if !defined(USE_PBC)
/* Precomputations of generators in G1 and G2 */
crs.v1._2.precomputeForMult();
crs.v2._2.precomputeForMult();
/* Precomputations for commitments of scalars */
crs.u1._1.precomputeForMult();
crs.u1._2.precomputeForMult();
crs.u2._1.precomputeForMult();
crs.u2._2.precomputeForMult();
#endif
} else {
stream >> crs.v1._2 >> crs.v2._2;
stream >> crs.i1 >> crs.j1 >> crs.i2 >> crs.j2;
crs.computeElements();
}
return stream;
}
void CRS::computeElements() {
#if !defined(USE_PBC)
/* Precomputations of generators in G1 and G2 */
v1._2.precomputeForMult();
v2._2.precomputeForMult();
#endif
v1._1 = j1 * v1._2;
w1._1 = (i1 * j1) * v1._2;
u1._1 = w1._1;
v2._1 = j2 * v2._2;
w2._1 = (i2 * j2) * v2._2;
u2._1 = w2._1;
if (type == CRS_TYPE_EXTRACT) {
w1._2 = i1 * v1._2;
u1._2 = w1._2 + v1._2;
w2._2 = i2 * v2._2;
u2._2 = w2._2 + v2._2;
} else {
u1._2 = i1 * v1._2;
w1._2 = w1._2 - v1._2;
u2._2 = i2 * v2._2;
w2._2 = w2._2 - v2._2;
}
#if !defined(USE_PBC)
/* Precomputations for commitments of scalars */
crs.u1._1.precomputeForMult();
crs.u1._2.precomputeForMult();
crs.u2._1.precomputeForMult();
crs.u2._2.precomputeForMult();
#endif
}
}
<commit_msg>Efficiency improvement (memory)<commit_after>#include "maps.h"
namespace gsnizk {
G1 B1::extract(const CRS &crs) const {
return _2 - (Fp(1) / crs.j1) * _1;
}
G2 B2::extract(const CRS &crs) const {
return _2 - (Fp(1) / crs.j2) * _1;
}
GT BT::extract(const CRS &crs) const {
Fp p = Fp(-1) / crs.j1;
return (_22 * (_12 ^ p)) * ((_21 * (_11 ^ p)) ^ (Fp(-1) / crs.j2));
}
BT BT::pairing(const B1 &a, const B2 &b) {
// TODO precompute pairings?
return BT(GT::pairing(a._1, b._1), GT::pairing(a._1, b._2),
GT::pairing(a._2, b._1), GT::pairing(a._2, b._2));
}
BT BT::pairing(const std::vector<std::pair<B1, B2> > &lst) {
// TODO precompute pairings?
std::vector<std::pair<G1, G2> > p11, p12, p21, p22;
p11.reserve(lst.size());
p12.reserve(lst.size());
p21.reserve(lst.size());
p22.reserve(lst.size());
for (const std::pair<B1, B2> p: lst) {
p11.push_back(std::pair<G1, G2>(p.first._1, p.second._1));
p12.push_back(std::pair<G1, G2>(p.first._1, p.second._2));
p21.push_back(std::pair<G1, G2>(p.first._2, p.second._1));
p22.push_back(std::pair<G1, G2>(p.first._2, p.second._2));
}
return BT(GT::pairing(p11), GT::pairing(p12),
GT::pairing(p21), GT::pairing(p22));
}
CRS::CRS(bool binding) : v1(G1(), G1::getRand()), v2(G2(), G2::getRand()),
type(binding ? CRS_TYPE_EXTRACT : CRS_TYPE_ZK),
i1(Fp::getRand()), j1(Fp::getRand()),
i2(Fp::getRand()), j2(Fp::getRand())
{
computeElements();
}
void CRS::makePublic() {
if (type != CRS_TYPE_PUBLIC) {
i1 = Fp();
i2 = Fp();
type = CRS_TYPE_PUBLIC;
}
}
std::ostream &operator<<(std::ostream &stream, const CRS &crs) {
stream << crs.type;
if (crs.type == CRS_TYPE_PUBLIC) {
stream << crs.v1 << crs.w1;
stream << crs.v2 << crs.w2;
} else {
stream << crs.v1._2 << crs.v2._2;
stream << crs.i1 << crs.j1 << crs.i2 << crs.j2;
}
return stream;
}
std::istream &operator>>(std::istream &stream, CRS &crs) {
stream >> crs.type;
// TODO precomputations?
if (crs.type == CRS_TYPE_PUBLIC) {
stream >> crs.v1 >> crs.w1;
stream >> crs.v2 >> crs.w2;
crs.u1._1 = crs.w1._1;
crs.u1._2 = crs.w1._2 + crs.v1._2;
crs.u2._1 = crs.w2._1;
crs.u2._2 = crs.w2._2 + crs.v2._2;
#if !defined(USE_PBC)
/* Precomputations of generators in G1 and G2 */
crs.v1._2.precomputeForMult();
crs.v2._2.precomputeForMult();
/* Precomputations for commitments of scalars */
crs.u1._1.precomputeForMult();
crs.u1._2.precomputeForMult();
crs.u2._1.precomputeForMult();
crs.u2._2.precomputeForMult();
#endif
} else {
stream >> crs.v1._2 >> crs.v2._2;
stream >> crs.i1 >> crs.j1 >> crs.i2 >> crs.j2;
crs.computeElements();
}
return stream;
}
void CRS::computeElements() {
#if !defined(USE_PBC)
/* Precomputations of generators in G1 and G2 */
v1._2.precomputeForMult();
v2._2.precomputeForMult();
#endif
v1._1 = j1 * v1._2;
w1._1 = (i1 * j1) * v1._2;
u1._1 = w1._1;
v2._1 = j2 * v2._2;
w2._1 = (i2 * j2) * v2._2;
u2._1 = w2._1;
if (type == CRS_TYPE_EXTRACT) {
w1._2 = i1 * v1._2;
u1._2 = w1._2 + v1._2;
w2._2 = i2 * v2._2;
u2._2 = w2._2 + v2._2;
} else {
u1._2 = i1 * v1._2;
w1._2 = w1._2 - v1._2;
u2._2 = i2 * v2._2;
w2._2 = w2._2 - v2._2;
}
#if !defined(USE_PBC)
/* Precomputations for commitments of scalars */
u1._1.precomputeForMult();
u1._2.precomputeForMult();
u2._1.precomputeForMult();
u2._2.precomputeForMult();
#endif
}
}
<|endoftext|>
|
<commit_before>
/*******************************************************************************
** Copyright Chris Scott 2014
** Interface to Voro++
*******************************************************************************/
#include "stdlib.h"
#include "math.h"
#include "voro_iface.h"
#include "voro++.hh"
#include <vector>
using namespace voro;
static int processAtomCell(voronoicell_neighbor&, int, double*, double, vorores_t*);
/*******************************************************************************
* Main interface function to be called from C
*******************************************************************************/
extern "C" int computeVoronoiVoroPlusPlusWrapper(int NAtoms, double *pos, int *PBC,
double *bound_lo, double *bound_hi, int useRadii, double *radii,
double faceAreaThreshold, vorores_t *voroResult)
{
int i;
/* number of cells for spatial decomposition */
double n[3];
for (i = 0; i < 3; i++) n[i] = bound_hi[i] - bound_lo[i];
double V = n[0] * n[1] * n[2];
for (i = 0; i < 3; i++)
{
n[i] = round(n[i] * pow(double(NAtoms) / (V * 8.0), 0.333333));
n[i] = n[i] == 0 ? 1 : n[i];
// printf("DEBUG: n[%d] = %lf\n", i, n[i]);
}
// voro cell with neighbour information
voronoicell_neighbor c;
// use radii or not
if (useRadii)
{
/* initialise voro++ container, preallocates 8 atoms per cell */
container_poly con(bound_lo[0], bound_hi[0],
bound_lo[1], bound_hi[1],
bound_lo[2], bound_hi[2],
int(n[0]),int(n[1]),int(n[2]),
bool(PBC[0]), bool(PBC[1]), bool(PBC[2]), 8);
// pass coordinates for local and ghost atoms to voro++
for (i = 0; i < NAtoms; i++)
con.put(i, pos[3*i], pos[3*i+1], pos[3*i+2], radii[i]);
// invoke voro++ and fetch results for owned atoms in group
int count = 0;
c_loop_all cl(con);
if (cl.start()) do if (con.compute_cell(c,cl))
{
i = cl.pid();
processAtomCell(c, i, pos, faceAreaThreshold, voroResult);
count++;
} while (cl.inc());
// printf("DEBUG: COUNT = %d (%d atoms)\n", count, NAtoms);
}
else
{
/* initialise voro++ container, preallocates 8 atoms per cell */
container con(bound_lo[0], bound_hi[0],
bound_lo[1], bound_hi[1],
bound_lo[2], bound_hi[2],
int(n[0]),int(n[1]),int(n[2]),
bool(PBC[0]), bool(PBC[1]), bool(PBC[2]), 8);
// pass coordinates for local and ghost atoms to voro++
for (i = 0; i < NAtoms; i++)
con.put(i, pos[3*i], pos[3*i+1], pos[3*i+2]);
// invoke voro++ and fetch results for owned atoms in group
int count = 0;
int errcnt = 0;
c_loop_all cl(con);
if (cl.start()) do if (con.compute_cell(c,cl))
{
int retval;
i = cl.pid();
retval = processAtomCell(c, i, pos, faceAreaThreshold, voroResult);
if (retval)
{
errcnt++;
}
count++;
} while (cl.inc());
// printf("DEBUG: COUNT = %d (%d atoms)\n", count, NAtoms);
/* return error */
if (errcnt) return -1;
}
return 0;
}
/*******************************************************************************
* Process cell; compute volume, num neighbours, facets etc.
*******************************************************************************/
static int processAtomCell(voronoicell_neighbor &c, int i, double *pos, double fthresh, vorores_t *voroResult)
{
/* initialise result */
voroResult[i].numFaces = 0;
voroResult[i].numNeighbours = 0;
voroResult[i].numVertices = 0;
/* volume */
voroResult[i].volume = c.volume();
/* number of neighbours */
std::vector<int> neighbours;
c.neighbors(neighbours);
unsigned int nnebs = neighbours.size();
voroResult[i].neighbours = (int*) malloc(nnebs * sizeof(int));
if (voroResult[i].neighbours == NULL) return -1;
if (fthresh > 0)
{
/* area of faces */
std::vector<double> narea;
c.face_areas(narea);
if (nnebs != narea.size()) printf("****************VOROERROR!\n");
int nnebstrue = 0;
for (unsigned int j = 0; j < nnebs; j++)
{
if (narea[j] > fthresh) voroResult[i].neighbours[nnebstrue++] = neighbours[j];
}
voroResult[i].neighbours = (int*) realloc(voroResult[i].neighbours, nnebstrue * sizeof(int));
voroResult[i].numNeighbours = nnebstrue;
}
else
{
for (unsigned int j = 0; j < nnebs; j++)
voroResult[i].neighbours[j] = neighbours[j];
voroResult[i].numNeighbours = nnebs;
}
/* vertices */
std::vector<double> vertices;
c.vertices(pos[3*i], pos[3*i+1], pos[3*i+2], vertices);
int nvertices = c.p;
voroResult[i].vertices = (double*) malloc(3 * nvertices * sizeof(double));
if (voroResult[i].vertices == NULL) return -1;
for (int j = 0; j < nvertices; j++)
{
int j3 = 3 * j;
voroResult[i].vertices[j3] = vertices[j3];
voroResult[i].vertices[j3+1] = vertices[j3+1];
voroResult[i].vertices[j3+2] = vertices[j3+2];
}
voroResult[i].numVertices = nvertices;
/* faces */
std::vector<int> faceVertices;
c.face_vertices(faceVertices);
int nfaces = c.number_of_faces();
voroResult[i].numFaceVertices = (int*) calloc(nfaces, sizeof(int));
if (voroResult[i].numFaceVertices == NULL) return -1;
voroResult[i].faceVertices = (int**) malloc(nfaces * sizeof(int*));
if (voroResult[i].faceVertices == NULL) return -1;
voroResult[i].numFaces = nfaces;
int count = 0;
for (int j = 0; j < nfaces; j++)
{
int nfaceverts = faceVertices[count++];
/* allocate space for this faces vertices */
voroResult[i].faceVertices[j] = (int*) malloc(nfaceverts * sizeof(int));
if (voroResult[i].faceVertices[j] == NULL) return -1;
voroResult[i].numFaceVertices[j] = nfaceverts;
for (int k = 0; k < nfaceverts; k++)
voroResult[i].faceVertices[j][k] = faceVertices[count++];
}
/* original position */
voroResult[i].originalPos[0] = pos[3*i];
voroResult[i].originalPos[1] = pos[3*i+1];
voroResult[i].originalPos[2] = pos[3*i+2];
return 0;
}
<commit_msg>Only realloc neighbours array if size changed.<commit_after>
/*******************************************************************************
** Copyright Chris Scott 2014
** Interface to Voro++
*******************************************************************************/
#include "stdlib.h"
#include "math.h"
#include "voro_iface.h"
#include "voro++.hh"
#include <vector>
using namespace voro;
static int processAtomCell(voronoicell_neighbor&, int, double*, double, vorores_t*);
/*******************************************************************************
* Main interface function to be called from C
*******************************************************************************/
extern "C" int computeVoronoiVoroPlusPlusWrapper(int NAtoms, double *pos, int *PBC,
double *bound_lo, double *bound_hi, int useRadii, double *radii,
double faceAreaThreshold, vorores_t *voroResult)
{
int i;
/* number of cells for spatial decomposition */
double n[3];
for (i = 0; i < 3; i++) n[i] = bound_hi[i] - bound_lo[i];
double V = n[0] * n[1] * n[2];
for (i = 0; i < 3; i++)
{
n[i] = round(n[i] * pow(double(NAtoms) / (V * 8.0), 0.333333));
n[i] = n[i] == 0 ? 1 : n[i];
// printf("DEBUG: n[%d] = %lf\n", i, n[i]);
}
// voro cell with neighbour information
voronoicell_neighbor c;
// use radii or not
if (useRadii)
{
/* initialise voro++ container, preallocates 8 atoms per cell */
container_poly con(bound_lo[0], bound_hi[0],
bound_lo[1], bound_hi[1],
bound_lo[2], bound_hi[2],
int(n[0]),int(n[1]),int(n[2]),
bool(PBC[0]), bool(PBC[1]), bool(PBC[2]), 8);
// pass coordinates for local and ghost atoms to voro++
for (i = 0; i < NAtoms; i++)
con.put(i, pos[3*i], pos[3*i+1], pos[3*i+2], radii[i]);
// invoke voro++ and fetch results for owned atoms in group
int count = 0;
c_loop_all cl(con);
if (cl.start()) do if (con.compute_cell(c,cl))
{
i = cl.pid();
processAtomCell(c, i, pos, faceAreaThreshold, voroResult);
count++;
} while (cl.inc());
// printf("DEBUG: COUNT = %d (%d atoms)\n", count, NAtoms);
}
else
{
/* initialise voro++ container, preallocates 8 atoms per cell */
container con(bound_lo[0], bound_hi[0],
bound_lo[1], bound_hi[1],
bound_lo[2], bound_hi[2],
int(n[0]),int(n[1]),int(n[2]),
bool(PBC[0]), bool(PBC[1]), bool(PBC[2]), 8);
// pass coordinates for local and ghost atoms to voro++
for (i = 0; i < NAtoms; i++)
con.put(i, pos[3*i], pos[3*i+1], pos[3*i+2]);
// invoke voro++ and fetch results for owned atoms in group
int count = 0;
int errcnt = 0;
c_loop_all cl(con);
if (cl.start()) do if (con.compute_cell(c,cl))
{
int retval;
i = cl.pid();
retval = processAtomCell(c, i, pos, faceAreaThreshold, voroResult);
if (retval)
{
errcnt++;
}
count++;
} while (cl.inc());
// printf("DEBUG: COUNT = %d (%d atoms)\n", count, NAtoms);
/* return error */
if (errcnt) return -1;
}
return 0;
}
/*******************************************************************************
* Process cell; compute volume, num neighbours, facets etc.
*******************************************************************************/
static int processAtomCell(voronoicell_neighbor &c, int i, double *pos, double fthresh, vorores_t *voroResult)
{
/* initialise result */
voroResult[i].numFaces = 0;
voroResult[i].numNeighbours = 0;
voroResult[i].numVertices = 0;
/* volume */
voroResult[i].volume = c.volume();
/* number of neighbours */
std::vector<int> neighbours;
c.neighbors(neighbours);
unsigned int nnebs = neighbours.size();
voroResult[i].neighbours = (int*) malloc(nnebs * sizeof(int));
if (voroResult[i].neighbours == NULL) return -1;
if (fthresh > 0)
{
/* area of faces */
std::vector<double> narea;
c.face_areas(narea);
if (nnebs != narea.size()) printf("****************VOROERROR!\n");
unsigned int nnebstrue = 0;
for (unsigned int j = 0; j < nnebs; j++)
{
if (narea[j] > fthresh) voroResult[i].neighbours[nnebstrue++] = neighbours[j];
}
if (nnebs != nnebstrue) voroResult[i].neighbours = (int*) realloc(voroResult[i].neighbours, nnebstrue * sizeof(int));
voroResult[i].numNeighbours = nnebstrue;
}
else
{
for (unsigned int j = 0; j < nnebs; j++)
voroResult[i].neighbours[j] = neighbours[j];
voroResult[i].numNeighbours = nnebs;
}
/* vertices */
std::vector<double> vertices;
c.vertices(pos[3*i], pos[3*i+1], pos[3*i+2], vertices);
int nvertices = c.p;
voroResult[i].vertices = (double*) malloc(3 * nvertices * sizeof(double));
if (voroResult[i].vertices == NULL) return -1;
for (int j = 0; j < nvertices; j++)
{
int j3 = 3 * j;
voroResult[i].vertices[j3] = vertices[j3];
voroResult[i].vertices[j3+1] = vertices[j3+1];
voroResult[i].vertices[j3+2] = vertices[j3+2];
}
voroResult[i].numVertices = nvertices;
/* faces */
std::vector<int> faceVertices;
c.face_vertices(faceVertices);
int nfaces = c.number_of_faces();
voroResult[i].numFaceVertices = (int*) calloc(nfaces, sizeof(int));
if (voroResult[i].numFaceVertices == NULL) return -1;
voroResult[i].faceVertices = (int**) malloc(nfaces * sizeof(int*));
if (voroResult[i].faceVertices == NULL) return -1;
voroResult[i].numFaces = nfaces;
int count = 0;
for (int j = 0; j < nfaces; j++)
{
int nfaceverts = faceVertices[count++];
/* allocate space for this faces vertices */
voroResult[i].faceVertices[j] = (int*) malloc(nfaceverts * sizeof(int));
if (voroResult[i].faceVertices[j] == NULL) return -1;
voroResult[i].numFaceVertices[j] = nfaceverts;
for (int k = 0; k < nfaceverts; k++)
voroResult[i].faceVertices[j][k] = faceVertices[count++];
}
/* original position */
voroResult[i].originalPos[0] = pos[3*i];
voroResult[i].originalPos[1] = pos[3*i+1];
voroResult[i].originalPos[2] = pos[3*i+2];
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 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/renderer/tts_dispatcher.h"
#include "base/basictypes.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/tts_messages.h"
#include "chrome/common/tts_utterance_request.h"
#include "content/public/renderer/render_thread.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebCString.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebSpeechSynthesisUtterance.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebSpeechSynthesisVoice.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebString.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebVector.h"
using content::RenderThread;
using WebKit::WebSpeechSynthesizerClient;
using WebKit::WebSpeechSynthesisUtterance;
using WebKit::WebSpeechSynthesisVoice;
using WebKit::WebString;
using WebKit::WebVector;
int TtsDispatcher::next_utterance_id_ = 1;
TtsDispatcher::TtsDispatcher(WebSpeechSynthesizerClient* client)
: synthesizer_client_(client) {
RenderThread::Get()->AddObserver(this);
}
TtsDispatcher::~TtsDispatcher() {
}
bool TtsDispatcher::OnControlMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(TtsDispatcher, message)
IPC_MESSAGE_HANDLER(TtsMsg_SetVoiceList, OnSetVoiceList)
IPC_MESSAGE_HANDLER(TtsMsg_DidStartSpeaking, OnDidStartSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_DidFinishSpeaking, OnDidFinishSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_DidPauseSpeaking, OnDidPauseSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_DidResumeSpeaking, OnDidResumeSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_WordBoundary, OnWordBoundary)
IPC_MESSAGE_HANDLER(TtsMsg_SentenceBoundary, OnSentenceBoundary)
IPC_MESSAGE_HANDLER(TtsMsg_MarkerEvent, OnMarkerEvent)
IPC_MESSAGE_HANDLER(TtsMsg_WasInterrupted, OnWasInterrupted)
IPC_MESSAGE_HANDLER(TtsMsg_WasCancelled, OnWasCancelled)
IPC_MESSAGE_HANDLER(TtsMsg_SpeakingErrorOccurred, OnSpeakingErrorOccurred)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void TtsDispatcher::updateVoiceList() {
RenderThread::Get()->Send(new TtsHostMsg_InitializeVoiceList());
}
void TtsDispatcher::speak(const WebSpeechSynthesisUtterance& web_utterance) {
int id = next_utterance_id_++;
utterance_id_map_[id] = web_utterance;
TtsUtteranceRequest utterance;
utterance.id = id;
utterance.text = web_utterance.text().utf8();
utterance.lang = web_utterance.lang().utf8();
utterance.voice = web_utterance.voice().utf8();
utterance.volume = web_utterance.volume();
utterance.rate = web_utterance.rate();
utterance.pitch = web_utterance.pitch();
RenderThread::Get()->Send(new TtsHostMsg_Speak(utterance));
}
void TtsDispatcher::pause() {
RenderThread::Get()->Send(new TtsHostMsg_Pause());
}
void TtsDispatcher::resume() {
RenderThread::Get()->Send(new TtsHostMsg_Resume());
}
void TtsDispatcher::cancel() {
RenderThread::Get()->Send(new TtsHostMsg_Cancel());
}
WebSpeechSynthesisUtterance TtsDispatcher::FindUtterance(int utterance_id) {
base::hash_map<int, WebSpeechSynthesisUtterance>::const_iterator iter =
utterance_id_map_.find(utterance_id);
if (iter == utterance_id_map_.end())
return WebSpeechSynthesisUtterance();
return iter->second;
}
void TtsDispatcher::OnSetVoiceList(const std::vector<TtsVoice>& voices) {
WebVector<WebSpeechSynthesisVoice> out_voices(voices.size());
for (size_t i = 0; i < voices.size(); ++i) {
out_voices[i] = WebSpeechSynthesisVoice();
out_voices[i].setVoiceURI(WebString::fromUTF8(voices[i].voice_uri));
out_voices[i].setName(WebString::fromUTF8(voices[i].name));
out_voices[i].setLanguage(WebString::fromUTF8(voices[i].lang));
out_voices[i].setIsLocalService(voices[i].local_service);
out_voices[i].setIsDefault(voices[i].is_default);
}
synthesizer_client_->setVoiceList(out_voices);
}
void TtsDispatcher::OnDidStartSpeaking(int utterance_id) {
if (utterance_id_map_.find(utterance_id) == utterance_id_map_.end())
return;
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didStartSpeaking(utterance);
}
void TtsDispatcher::OnDidFinishSpeaking(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didFinishSpeaking(utterance);
utterance_id_map_.erase(utterance_id);
}
void TtsDispatcher::OnDidPauseSpeaking(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didPauseSpeaking(utterance);
}
void TtsDispatcher::OnDidResumeSpeaking(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didResumeSpeaking(utterance);
}
void TtsDispatcher::OnWordBoundary(int utterance_id, int char_index) {
CHECK(char_index >= 0);
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->wordBoundaryEventOccurred(
utterance, static_cast<unsigned>(char_index));
}
void TtsDispatcher::OnSentenceBoundary(int utterance_id, int char_index) {
CHECK(char_index >= 0);
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->sentenceBoundaryEventOccurred(
utterance, static_cast<unsigned>(char_index));
}
void TtsDispatcher::OnMarkerEvent(int utterance_id, int char_index) {
// Not supported yet.
}
void TtsDispatcher::OnWasInterrupted(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
// The web speech API doesn't support "interrupted".
synthesizer_client_->didFinishSpeaking(utterance);
utterance_id_map_.erase(utterance_id);
}
void TtsDispatcher::OnWasCancelled(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
// The web speech API doesn't support "cancelled".
synthesizer_client_->didFinishSpeaking(utterance);
utterance_id_map_.erase(utterance_id);
}
void TtsDispatcher::OnSpeakingErrorOccurred(int utterance_id,
const std::string& error_message) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
// The web speech API doesn't support an error message.
synthesizer_client_->speakingErrorOccurred(utterance);
utterance_id_map_.erase(utterance_id);
}
<commit_msg>Don't forget to call RemoveObserver when TtsDispatcher is destroyed.<commit_after>// Copyright (c) 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/renderer/tts_dispatcher.h"
#include "base/basictypes.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/tts_messages.h"
#include "chrome/common/tts_utterance_request.h"
#include "content/public/renderer/render_thread.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebCString.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebSpeechSynthesisUtterance.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebSpeechSynthesisVoice.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebString.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebVector.h"
using content::RenderThread;
using WebKit::WebSpeechSynthesizerClient;
using WebKit::WebSpeechSynthesisUtterance;
using WebKit::WebSpeechSynthesisVoice;
using WebKit::WebString;
using WebKit::WebVector;
int TtsDispatcher::next_utterance_id_ = 1;
TtsDispatcher::TtsDispatcher(WebSpeechSynthesizerClient* client)
: synthesizer_client_(client) {
RenderThread::Get()->AddObserver(this);
}
TtsDispatcher::~TtsDispatcher() {
RenderThread::Get()->RemoveObserver(this);
}
bool TtsDispatcher::OnControlMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(TtsDispatcher, message)
IPC_MESSAGE_HANDLER(TtsMsg_SetVoiceList, OnSetVoiceList)
IPC_MESSAGE_HANDLER(TtsMsg_DidStartSpeaking, OnDidStartSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_DidFinishSpeaking, OnDidFinishSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_DidPauseSpeaking, OnDidPauseSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_DidResumeSpeaking, OnDidResumeSpeaking)
IPC_MESSAGE_HANDLER(TtsMsg_WordBoundary, OnWordBoundary)
IPC_MESSAGE_HANDLER(TtsMsg_SentenceBoundary, OnSentenceBoundary)
IPC_MESSAGE_HANDLER(TtsMsg_MarkerEvent, OnMarkerEvent)
IPC_MESSAGE_HANDLER(TtsMsg_WasInterrupted, OnWasInterrupted)
IPC_MESSAGE_HANDLER(TtsMsg_WasCancelled, OnWasCancelled)
IPC_MESSAGE_HANDLER(TtsMsg_SpeakingErrorOccurred, OnSpeakingErrorOccurred)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void TtsDispatcher::updateVoiceList() {
RenderThread::Get()->Send(new TtsHostMsg_InitializeVoiceList());
}
void TtsDispatcher::speak(const WebSpeechSynthesisUtterance& web_utterance) {
int id = next_utterance_id_++;
utterance_id_map_[id] = web_utterance;
TtsUtteranceRequest utterance;
utterance.id = id;
utterance.text = web_utterance.text().utf8();
utterance.lang = web_utterance.lang().utf8();
utterance.voice = web_utterance.voice().utf8();
utterance.volume = web_utterance.volume();
utterance.rate = web_utterance.rate();
utterance.pitch = web_utterance.pitch();
RenderThread::Get()->Send(new TtsHostMsg_Speak(utterance));
}
void TtsDispatcher::pause() {
RenderThread::Get()->Send(new TtsHostMsg_Pause());
}
void TtsDispatcher::resume() {
RenderThread::Get()->Send(new TtsHostMsg_Resume());
}
void TtsDispatcher::cancel() {
RenderThread::Get()->Send(new TtsHostMsg_Cancel());
}
WebSpeechSynthesisUtterance TtsDispatcher::FindUtterance(int utterance_id) {
base::hash_map<int, WebSpeechSynthesisUtterance>::const_iterator iter =
utterance_id_map_.find(utterance_id);
if (iter == utterance_id_map_.end())
return WebSpeechSynthesisUtterance();
return iter->second;
}
void TtsDispatcher::OnSetVoiceList(const std::vector<TtsVoice>& voices) {
WebVector<WebSpeechSynthesisVoice> out_voices(voices.size());
for (size_t i = 0; i < voices.size(); ++i) {
out_voices[i] = WebSpeechSynthesisVoice();
out_voices[i].setVoiceURI(WebString::fromUTF8(voices[i].voice_uri));
out_voices[i].setName(WebString::fromUTF8(voices[i].name));
out_voices[i].setLanguage(WebString::fromUTF8(voices[i].lang));
out_voices[i].setIsLocalService(voices[i].local_service);
out_voices[i].setIsDefault(voices[i].is_default);
}
synthesizer_client_->setVoiceList(out_voices);
}
void TtsDispatcher::OnDidStartSpeaking(int utterance_id) {
if (utterance_id_map_.find(utterance_id) == utterance_id_map_.end())
return;
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didStartSpeaking(utterance);
}
void TtsDispatcher::OnDidFinishSpeaking(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didFinishSpeaking(utterance);
utterance_id_map_.erase(utterance_id);
}
void TtsDispatcher::OnDidPauseSpeaking(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didPauseSpeaking(utterance);
}
void TtsDispatcher::OnDidResumeSpeaking(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->didResumeSpeaking(utterance);
}
void TtsDispatcher::OnWordBoundary(int utterance_id, int char_index) {
CHECK(char_index >= 0);
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->wordBoundaryEventOccurred(
utterance, static_cast<unsigned>(char_index));
}
void TtsDispatcher::OnSentenceBoundary(int utterance_id, int char_index) {
CHECK(char_index >= 0);
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
synthesizer_client_->sentenceBoundaryEventOccurred(
utterance, static_cast<unsigned>(char_index));
}
void TtsDispatcher::OnMarkerEvent(int utterance_id, int char_index) {
// Not supported yet.
}
void TtsDispatcher::OnWasInterrupted(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
// The web speech API doesn't support "interrupted".
synthesizer_client_->didFinishSpeaking(utterance);
utterance_id_map_.erase(utterance_id);
}
void TtsDispatcher::OnWasCancelled(int utterance_id) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
// The web speech API doesn't support "cancelled".
synthesizer_client_->didFinishSpeaking(utterance);
utterance_id_map_.erase(utterance_id);
}
void TtsDispatcher::OnSpeakingErrorOccurred(int utterance_id,
const std::string& error_message) {
WebSpeechSynthesisUtterance utterance = FindUtterance(utterance_id);
if (utterance.isNull())
return;
// The web speech API doesn't support an error message.
synthesizer_client_->speakingErrorOccurred(utterance);
utterance_id_map_.erase(utterance_id);
}
<|endoftext|>
|
<commit_before>#include "allocator.h"
#include <cstring>
namespace nvds {
uintptr_t Allocator::Alloc(uint32_t size) {
// The client side should refuse too big kv item.
// TODO(wgtdkp): round up.
auto blk_size = size + sizeof(uint32_t);
assert(blk_size % 16 == 0);
assert(blk_size <= kMaxBlockSize);
auto blk = AllocBlock(blk_size);
return blk == 0 ? 0 : blk + sizeof(uint32_t) + base_;
}
// A nullptr(0) is not going to be accepted.
void Allocator::Free(uintptr_t ptr) {
// TODO(wgtdkp): Checking if ptr is actually in this Allocator zone.
assert(ptr >= base_ + sizeof(uint32_t) && ptr <= base_ + kSize);
auto blk = ptr - sizeof(uint32_t) - base_;
FreeBlock(blk);
}
void Allocator::Format() {
static_assert(sizeof(FreeListManager) == 512 * 1024,
"Wrong FreeListManager size");
memset(flm_, 0, sizeof(FreeListManager));
uint32_t free_list = (kNumFreeList / 2 - 1) * sizeof(uint32_t);
uint32_t blk = sizeof(FreeListManager);
// 'The block before first block' is not free
Write(blk, ~BlockHeader::kFreeMask & kMaxBlockSize);
for (; blk + kMaxBlockSize + sizeof(uint32_t) <= kSize; blk += kMaxBlockSize) {
auto head = Read<uint32_t>(free_list);
if (head != 0) {
Write(head + offsetof(BlockHeader, prev), blk);
}
Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
Write(blk + offsetof(BlockHeader, next), head);
Write(blk, ReadThePrevFreeTag(blk) | kMaxBlockSize);
Write(blk + kMaxBlockSize - sizeof(uint32_t), kMaxBlockSize);
SetTheFreeTag(blk, kMaxBlockSize);
Write(free_list, blk);
}
}
uint32_t Allocator::AllocBlock(uint32_t blk_size) {
uint32_t idx = blk_size / 16 - 1;
for (uint32_t i = idx; i < kNumFreeList; ++i) {
auto free_list = i * sizeof(uint32_t);
auto head = Read<uint32_t>(free_list);
auto head_size = (i + 1) * 16;
if (head == 0)
continue;
if (i == idx) {
auto next_blk = Read<uint32_t>(head + offsetof(BlockHeader, next));
ResetTheFreeTag(head, head_size);
Write(free_list, next_blk);
Write(next_blk + offsetof(BlockHeader, prev),
static_cast<uint32_t>(0));
return head;
} else {
if (free_list == 262140) {
free_list = 262140;
}
return SplitBlock(head, head_size, blk_size);
}
}
return 0;
}
void Allocator::FreeBlock(uint32_t blk) {
auto blk_size = Read<uint32_t>(blk) & ~BlockHeader::kFreeMask;
auto blk_size_old = blk_size;
auto prev_blk_size = Read<uint32_t>(blk - sizeof(uint32_t));
auto prev_blk = blk - prev_blk_size;
auto next_blk = blk + blk_size;
auto next_blk_size = Read<uint32_t>(next_blk) & ~BlockHeader::kFreeMask;
if (blk_size + prev_blk_size <= 2 * kMaxBlockSize &&
ReadThePrevFreeTag(blk)) {
RemoveBlock(prev_blk, prev_blk_size);
blk = prev_blk;
blk_size += prev_blk_size;
}
if (blk_size + next_blk_size <= 2 * kMaxBlockSize &&
ReadTheFreeTag(next_blk, next_blk_size)) {
RemoveBlock(next_blk, next_blk_size);
blk_size += next_blk_size;
}
// If the blk_size changed, write it.
if (blk_size != blk_size_old) {
Write(blk, ReadThePrevFreeTag(blk) | blk_size);
Write(blk + blk_size - sizeof(uint32_t), blk_size);
}
SetTheFreeTag(blk, blk_size);
auto free_list = GetFreeListByBlockSize(blk_size);
auto head = Read<uint32_t>(free_list);
Write(free_list, blk);
Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
Write(blk + offsetof(BlockHeader, next), head);
if (head != 0) {
Write(head + offsetof(BlockHeader, prev), blk);
}
}
uint32_t Allocator::SplitBlock(uint32_t blk,
uint32_t blk_size,
uint32_t needed_size) {
auto next_blk = Read<uint32_t>(blk + offsetof(BlockHeader, next));
auto free_list = GetFreeListByBlockSize(blk_size);
auto new_size = blk_size - needed_size;
Write(free_list, next_blk);
if (next_blk != 0) {
Write(next_blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
}
// Update size
Write(blk, ReadThePrevFreeTag(blk) | new_size);
Write(blk + new_size - sizeof(uint32_t), new_size);
// Free the block after updating size
//FreeBlock(blk);
free_list = GetFreeListByBlockSize(new_size);
auto head = Read<uint32_t>(free_list);
Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
Write(blk + offsetof(BlockHeader, next), head);
Write(free_list, blk);
// The rest smaller block is still free
Write(blk + new_size, BlockHeader::kFreeMask | needed_size);
// Piece splitted is not free now.
ResetTheFreeTag(blk, blk_size);
return blk + new_size;
}
} // namespace nvds
<commit_msg>exchange bool expression order<commit_after>#include "allocator.h"
#include <cstring>
namespace nvds {
uintptr_t Allocator::Alloc(uint32_t size) {
// The client side should refuse too big kv item.
// TODO(wgtdkp): round up.
auto blk_size = size + sizeof(uint32_t);
assert(blk_size % 16 == 0);
assert(blk_size <= kMaxBlockSize);
auto blk = AllocBlock(blk_size);
return blk == 0 ? 0 : blk + sizeof(uint32_t) + base_;
}
// A nullptr(0) is not going to be accepted.
void Allocator::Free(uintptr_t ptr) {
// TODO(wgtdkp): Checking if ptr is actually in this Allocator zone.
assert(ptr >= base_ + sizeof(uint32_t) && ptr <= base_ + kSize);
auto blk = ptr - sizeof(uint32_t) - base_;
FreeBlock(blk);
}
void Allocator::Format() {
static_assert(sizeof(FreeListManager) == 512 * 1024,
"Wrong FreeListManager size");
memset(flm_, 0, sizeof(FreeListManager));
uint32_t free_list = (kNumFreeList / 2 - 1) * sizeof(uint32_t);
uint32_t blk = sizeof(FreeListManager);
// 'The block before first block' is not free
Write(blk, ~BlockHeader::kFreeMask & kMaxBlockSize);
for (; blk + kMaxBlockSize + sizeof(uint32_t) <= kSize; blk += kMaxBlockSize) {
auto head = Read<uint32_t>(free_list);
if (head != 0) {
Write(head + offsetof(BlockHeader, prev), blk);
}
Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
Write(blk + offsetof(BlockHeader, next), head);
Write(blk, ReadThePrevFreeTag(blk) | kMaxBlockSize);
Write(blk + kMaxBlockSize - sizeof(uint32_t), kMaxBlockSize);
SetTheFreeTag(blk, kMaxBlockSize);
Write(free_list, blk);
}
}
uint32_t Allocator::AllocBlock(uint32_t blk_size) {
uint32_t idx = blk_size / 16 - 1;
for (uint32_t i = idx; i < kNumFreeList; ++i) {
auto free_list = i * sizeof(uint32_t);
auto head = Read<uint32_t>(free_list);
auto head_size = (i + 1) * 16;
if (head == 0)
continue;
if (i == idx) {
auto next_blk = Read<uint32_t>(head + offsetof(BlockHeader, next));
ResetTheFreeTag(head, head_size);
Write(free_list, next_blk);
Write(next_blk + offsetof(BlockHeader, prev),
static_cast<uint32_t>(0));
return head;
} else {
if (free_list == 262140) {
free_list = 262140;
}
return SplitBlock(head, head_size, blk_size);
}
}
return 0;
}
void Allocator::FreeBlock(uint32_t blk) {
auto blk_size = Read<uint32_t>(blk) & ~BlockHeader::kFreeMask;
auto blk_size_old = blk_size;
auto prev_blk_size = Read<uint32_t>(blk - sizeof(uint32_t));
auto prev_blk = blk - prev_blk_size;
auto next_blk = blk + blk_size;
auto next_blk_size = Read<uint32_t>(next_blk) & ~BlockHeader::kFreeMask;
if (ReadThePrevFreeTag(blk) &&
blk_size + prev_blk_size <= 2 * kMaxBlockSize) {
RemoveBlock(prev_blk, prev_blk_size);
blk = prev_blk;
blk_size += prev_blk_size;
}
if (ReadTheFreeTag(next_blk, next_blk_size) &&
blk_size + next_blk_size <= 2 * kMaxBlockSize) {
RemoveBlock(next_blk, next_blk_size);
blk_size += next_blk_size;
}
// If the blk_size changed, write it.
if (blk_size != blk_size_old) {
Write(blk, ReadThePrevFreeTag(blk) | blk_size);
Write(blk + blk_size - sizeof(uint32_t), blk_size);
}
SetTheFreeTag(blk, blk_size);
auto free_list = GetFreeListByBlockSize(blk_size);
auto head = Read<uint32_t>(free_list);
Write(free_list, blk);
Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
Write(blk + offsetof(BlockHeader, next), head);
if (head != 0) {
Write(head + offsetof(BlockHeader, prev), blk);
}
}
uint32_t Allocator::SplitBlock(uint32_t blk,
uint32_t blk_size,
uint32_t needed_size) {
auto next_blk = Read<uint32_t>(blk + offsetof(BlockHeader, next));
auto free_list = GetFreeListByBlockSize(blk_size);
auto new_size = blk_size - needed_size;
Write(free_list, next_blk);
if (next_blk != 0) {
Write(next_blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
}
// Update size
Write(blk, ReadThePrevFreeTag(blk) | new_size);
Write(blk + new_size - sizeof(uint32_t), new_size);
// Free the block after updating size
//FreeBlock(blk);
free_list = GetFreeListByBlockSize(new_size);
auto head = Read<uint32_t>(free_list);
Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0));
Write(blk + offsetof(BlockHeader, next), head);
Write(free_list, blk);
// The rest smaller block is still free
Write(blk + new_size, BlockHeader::kFreeMask | needed_size);
// Piece splitted is not free now.
ResetTheFreeTag(blk, blk_size);
return blk + new_size;
}
} // namespace nvds
<|endoftext|>
|
<commit_before><commit_msg>`floyd_warshall_shader_CSV_compute_task`: `internal_format` is `GL_R8`.<commit_after><|endoftext|>
|
<commit_before>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_FUNCTIONALS_DEFAULT_HH
#define DUNE_PYMOR_FUNCTIONALS_DEFAULT_HH
#include <dune/common/typetraits.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/la/container/interfaces.hh>
#include "interfaces.hh"
namespace Dune {
namespace Pymor {
namespace Functionals {
template< class VectorImp >
class VectorBased;
template< class VectorImp >
class VectorBasedTraits
{
public:
typedef VectorBased< VectorImp > derived_type;
typedef VectorImp ContainerType;
typedef VectorImp SourceType;
typedef derived_type FrozenType;
typedef typename SourceType::ScalarType ScalarType;
static_assert(std::is_base_of< Dune::Pymor::LA::VectorInterface< typename VectorImp::Traits >, ContainerType >::value,
"VectorImp must be derived from Dune::Pymor::LA::VectorInterface!");
};
template< class VectorImp >
class VectorBased
: public FunctionalInterface< VectorBasedTraits< VectorImp > >
, public LA::ProvidesContainer< VectorBasedTraits< VectorImp > >
{
public:
typedef VectorBasedTraits< VectorImp > Traits;
typedef typename Traits::derived_type ThisType;
typedef typename Traits::ContainerType ContainerType;
typedef typename Traits::SourceType SourceType;
typedef typename Traits::ScalarType ScalarType;
typedef typename Traits::FrozenType FrozenType;
/**
* \attention This class takes ownership of vector_ptr (in the sense, that you must not delete it manually)!
*/
VectorBased(const ContainerType* vector_ptr)
: vector_(vector_ptr)
{}
VectorBased(const std::shared_ptr< const ContainerType > vector_ptr)
: vector_(vector_ptr)
{}
bool linear() const
{
return true;
}
unsigned int dim_source() const
{
return vector_->dim();
}
ScalarType apply(const SourceType& source, const Parameter mu = Parameter()) const
throw (Exception::this_is_not_parametric, Exception::sizes_do_not_match)
{
if (!mu.empty()) DUNE_PYMOR_THROW(Exception::this_is_not_parametric,
"mu has to be empty if parametric() == false (is " << mu << ")!");
if (source.dim() != dim_source())
DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
"the dim of source (" << source.dim() << ") does not match the dim_source of this ("
<< dim_source() << ")!");
return vector_->dot(source);
}
FrozenType freeze_parameter(const Parameter mu = Parameter()) const
throw (Exception::this_is_not_parametric)
{
DUNE_PYMOR_THROW(Exception::this_is_not_parametric, "do not call freeze_parameter(" << mu << ")"
<< "if parametric() == false!");
return FrozenType(new ContainerType());
}
std::shared_ptr< const ContainerType > container() const
{
return vector_;
}
ContainerType* as_vector_and_return_copy() const
{
return new ContainerType(vector_.copy());
}
private:
std::shared_ptr< const ContainerType > vector_;
}; // class VectorBased
} // namespace Functionals
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_FUNCTIONALS_DEFAULT_HH
<commit_msg>[functionals.default] fixed as_vector()<commit_after>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_FUNCTIONALS_DEFAULT_HH
#define DUNE_PYMOR_FUNCTIONALS_DEFAULT_HH
#include <dune/common/typetraits.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/la/container/interfaces.hh>
#include "interfaces.hh"
namespace Dune {
namespace Pymor {
namespace Functionals {
template< class VectorImp >
class VectorBased;
template< class VectorImp >
class VectorBasedTraits
{
public:
typedef VectorBased< VectorImp > derived_type;
typedef VectorImp ContainerType;
typedef VectorImp SourceType;
typedef derived_type FrozenType;
typedef typename SourceType::ScalarType ScalarType;
static_assert(std::is_base_of< Dune::Pymor::LA::VectorInterface< typename VectorImp::Traits >, ContainerType >::value,
"VectorImp must be derived from Dune::Pymor::LA::VectorInterface!");
};
template< class VectorImp >
class VectorBased
: public FunctionalInterface< VectorBasedTraits< VectorImp > >
, public LA::ProvidesContainer< VectorBasedTraits< VectorImp > >
{
public:
typedef VectorBasedTraits< VectorImp > Traits;
typedef typename Traits::derived_type ThisType;
typedef typename Traits::ContainerType ContainerType;
typedef typename Traits::SourceType SourceType;
typedef typename Traits::ScalarType ScalarType;
typedef typename Traits::FrozenType FrozenType;
/**
* \attention This class takes ownership of vector_ptr (in the sense, that you must not delete it manually)!
*/
VectorBased(const ContainerType* vector_ptr)
: vector_(vector_ptr)
{}
VectorBased(const std::shared_ptr< const ContainerType > vector_ptr)
: vector_(vector_ptr)
{}
bool linear() const
{
return true;
}
unsigned int dim_source() const
{
return vector_->dim();
}
ScalarType apply(const SourceType& source, const Parameter mu = Parameter()) const
throw (Exception::this_is_not_parametric, Exception::sizes_do_not_match)
{
if (!mu.empty()) DUNE_PYMOR_THROW(Exception::this_is_not_parametric,
"mu has to be empty if parametric() == false (is " << mu << ")!");
if (source.dim() != dim_source())
DUNE_PYMOR_THROW(Exception::sizes_do_not_match,
"the dim of source (" << source.dim() << ") does not match the dim_source of this ("
<< dim_source() << ")!");
return vector_->dot(source);
}
FrozenType freeze_parameter(const Parameter mu = Parameter()) const
throw (Exception::this_is_not_parametric)
{
DUNE_PYMOR_THROW(Exception::this_is_not_parametric, "do not call freeze_parameter(" << mu << ")"
<< "if parametric() == false!");
return FrozenType(new ContainerType());
}
std::shared_ptr< const ContainerType > container() const
{
return vector_;
}
ContainerType* as_vector_and_return_ptr() const
{
return new ContainerType(vector_->copy());
}
private:
std::shared_ptr< const ContainerType > vector_;
}; // class VectorBased
} // namespace Functionals
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_FUNCTIONALS_DEFAULT_HH
<|endoftext|>
|
<commit_before>/* cclive
* Copyright (C) 2010-2013 Toni Gundogdu <[email protected]>
*
* This file is part of cclive <http://cclive.sourceforge.net/>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <ccinternal>
#include <iomanip>
#include <vector>
#include <ctime>
#include <boost/algorithm/string/classification.hpp> // is_any_of
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#ifndef foreach
#define foreach BOOST_FOREACH
#endif
#include <ccquvi>
#include <ccapplication>
#include <ccoptions>
#include <ccutil>
#include <cclog>
#include <ccre>
namespace cc
{
static void handle_fetch(const quvi_word type, void*)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
static void print_done()
{
cc::log << "done.\n";
}
static void handle_verify(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
print_done();
}
static void handle_resolve(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
#ifdef HAVE_LIBQUVI_0_9
static void status_callback_pt9(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVI_CALLBACK_STATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVI_CALLBACK_STATUS_HTTP_QUERY_METAINFO:
handle_verify(type);
break;
case QUVI_CALLBACK_STATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#else
static void status_callback_pt4(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVISTATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVISTATUS_VERIFY:
handle_verify(type);
break;
case QUVISTATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#endif
static int status_callback(long param, void *ptr)
{
const quvi_word status = quvi_loword(param);
const quvi_word type = quvi_hiword(param);
#ifdef HAVE_LIBQUVI_0_9
status_callback_pt9(status, type, ptr);
#else
status_callback_pt4(status, type, ptr);
#endif
cc::log << std::flush;
return QUVI_OK;
}
template<class Iterator>
static Iterator make_unique(Iterator first, Iterator last)
{
while (first != last)
{
Iterator next(first);
last = std::remove(++next, last, *first);
first = next;
}
return last;
}
static void print_retrying(const int retry,
const int max_retries,
const int retry_wait)
{
if (retry > 0)
{
cc::log
<< "Retrying "
<< retry
<< " of "
<< max_retries
<< " ... "
<< std::flush;
cc::wait(retry_wait);
}
}
static void print_checking(const int i, const int n)
{
if (n > 1) cc::log << "(" << i << " of " << n << ") ";
cc::log << "Checking ... " << std::flush;
}
static void print_quvi_error(const quvi::error& e)
{
cc::log << "libquvi: error: " << e.what() << std::endl;
}
namespace po = boost::program_options;
typedef std::vector<std::string> vst;
static application::exit_status
print_streams(const quvi::query& query, const quvi::options &qopts,
const vst& input)
{
const size_t n = input.size();
size_t i = 0;
foreach (std::string url, input)
{
try
{
print_checking(++i,n);
query.setup_curl();
const std::string r = query.streams(url, qopts);
print_done();
if (cc::opts.flags.print_streams)
{
vst a;
boost::split(a, r, boost::is_any_of("|,"));
foreach (const std::string s, a)
{
cc::log << s << "\n";
}
}
else
cc::log << std::setw(10) << r << " : " << url << std::endl;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
return application::error;
}
}
return application::ok;
}
static void read_from(std::istream& is, vst& dst)
{
std::string s;
char ch = 0;
while (is.get(ch))
s += ch;
std::istringstream iss(s);
std::copy(
std::istream_iterator<std::string >(iss),
std::istream_iterator<std::string >(),
std::back_inserter<vst>(dst)
);
}
static bool is_url(const std::string& s)
{
return strstr(const_cast<char*>(s.c_str()), "://") != NULL;
}
static void parse_prefer_format(const std::string& url, std::string& fmt,
const po::variables_map& map)
{
vst vb, va = map["prefer-format"].as<vst>();
foreach (const std::string s, va)
{
boost::split(vb, s, boost::is_any_of(":"));
if (vb.size() == 2)
{
// vb[0] = pattern
// vb[1] = format
if (cc::re::grep(vb[0], url))
{
fmt = vb[1];
return;
}
}
vb.clear();
}
}
static void set_stream(const std::string& url, quvi::options& qopts,
const po::variables_map& map)
{
std::string s = "default";
if (map.count("stream"))
s = map["stream"].as<std::string>();
else
{
if (map.count("prefer-format"))
parse_prefer_format(url, s, map);
}
qopts.stream = s;
}
static const char copyr[] =
"\n\nCopyright (C) 2010-2013 Toni Gundogdu <[email protected]>\n"
"cclive comes with ABSOLUTELY NO WARRANTY. You may redistribute copies of\n"
"cclive under the terms of the GNU Affero General Public License version\n"
"3 or later. For more information, see "
"<http://www.gnu.org/licenses/agpl.html>.\n\n"
"To contact the developers, please mail to "
"<[email protected]>";
static const application::exit_status print_version()
{
std::cout
<< "cclive "
#ifdef VN
<< VN
#else
<< PACKAGE_VERSION
#endif
<< "\n built on "
<< BUILD_TIME
<< " for " << CANONICAL_TARGET
<< "\n libquvi "
<< quvi::version()
<< "\n libquvi-scripts "
<< quvi_version(QUVI_VERSION_SCRIPTS)
<< copyr
<< std::endl;
return application::ok;
}
application::exit_status application::exec(int argc, char **argv)
{
try
{
opts.exec(argc,argv);
}
catch(const std::exception& e)
{
std::clog << "error: " << e.what() << std::endl;
return application::error;
}
const po::variables_map map = cc::opts.map();
// Dump and terminate options.
if (opts.flags.help)
{
std::cout << opts << std::flush;
return application::ok;
}
else if (opts.flags.print_config)
{
opts.dump();
return application::ok;
}
else if (opts.flags.version)
return print_version();
// --support
quvi::query query; // Throws quvi::error caught in main.cpp
if (opts.flags.support)
{
std::cout << quvi::support_to_s(query.support()) << std::flush;
return application::ok;
}
// Parse input.
vst input;
if (map.count("url") == 0)
read_from(std::cin, input);
else
{
vst args = map["url"].as< vst >();
foreach(std::string arg, args)
{
if (!is_url(arg))
{
std::ifstream f(arg.c_str());
if (f.is_open())
read_from(f, input);
else
{
std::clog
<< "error: "
<< arg
<< ": "
<< cc::perror("unable to open")
<< std::endl;
}
}
else
input.push_back(arg);
}
}
if (input.size() == 0)
{
std::clog << "error: no input urls" << std::endl;
return application::error;
}
// Remove duplicates.
input.erase(make_unique(input.begin(), input.end()), input.end());
// Set up quvi.
quvi::options qopts;
qopts.useragent = map["agent"].as<std::string>(); /* libquvi 0.9+ */
qopts.resolve = ! opts.flags.no_resolve;
qopts.statusfunc = status_callback;
// Omit flag.
bool omit = opts.flags.quiet;
// Go to background.
#ifdef HAVE_FORK
const bool background_given = opts.flags.background;
if (background_given)
{
// (Boost) Throws std::runtime_error if fails.
cc::go_background(map["log-file"].as<std::string>(), omit);
}
#endif
// Omit std output. Note that --background flips this above.
cc::log.push(cc::omit_sink(omit));
cc::log.setf(std::ios::fixed);
// Print streams.
if (opts.flags.print_streams)
return print_streams(query, qopts, input);
#if defined (HAVE_FORK) && defined (HAVE_GETPID)
if (background_given)
{
cc::log
<< "Running in background (pid: "
<< static_cast<long>(getpid())
<< ")."
<< std::endl;
}
#endif
// For each input URL.
const size_t n = input.size();
size_t i = 0;
const int max_retries = map["max-retries"].as<int>();
const int retry_wait = map["retry-wait"].as<int>();
exit_status es = ok;
foreach(std::string url, input)
{
++i;
try
{
int retry = 0;
while (retry <= max_retries)
{
print_retrying(retry, max_retries, retry_wait);
++retry;
print_checking(i, n);
quvi::media m;
try
{
set_stream(url, qopts, map);
_curl = query.setup_curl();
m = query.parse(url, qopts);
}
catch(const quvi::error& e)
{
if (e.cannot_retry())
throw e;
else
print_quvi_error(e);
}
cc::get(m, _curl);
break; // Stop retrying.
}
es = ok;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
es = application::error;
}
catch(const std::runtime_error& e)
{
cc::log << "error: " << e.what() << std::endl;
es = application::error;
}
}
return es;
}
} // namespace cc
// vim: set ts=2 sw=2 tw=72 expandtab:
<commit_msg>cc::application: Use cc:input<commit_after>/* cclive
* Copyright (C) 2010-2013 Toni Gundogdu <[email protected]>
*
* This file is part of cclive <http://cclive.sourceforge.net/>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <ccinternal>
#include <iomanip>
#include <vector>
#include <ctime>
#include <boost/algorithm/string/classification.hpp> // is_any_of
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#ifndef foreach
#define foreach BOOST_FOREACH
#endif
#include <ccquvi>
#include <ccapplication>
#include <ccoptions>
#include <ccinput>
#include <ccutil>
#include <cclog>
#include <ccre>
namespace cc
{
static void handle_fetch(const quvi_word type, void*)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
static void print_done()
{
cc::log << "done.\n";
}
static void handle_verify(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
print_done();
}
static void handle_resolve(const quvi_word type)
{
#ifdef HAVE_LIBQUVI_0_9
if (type == QUVI_CALLBACK_STATUS_DONE)
#else
if (type == QUVISTATUSTYPE_DONE)
#endif
cc::log << " ";
}
#ifdef HAVE_LIBQUVI_0_9
static void status_callback_pt9(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVI_CALLBACK_STATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVI_CALLBACK_STATUS_HTTP_QUERY_METAINFO:
handle_verify(type);
break;
case QUVI_CALLBACK_STATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#else
static void status_callback_pt4(const quvi_word status, const quvi_word type,
void *ptr)
{
cc::log << ".";
switch (status)
{
case QUVISTATUS_FETCH:
handle_fetch(type, ptr);
break;
case QUVISTATUS_VERIFY:
handle_verify(type);
break;
case QUVISTATUS_RESOLVE:
handle_resolve(type);
break;
}
}
#endif
static int status_callback(long param, void *ptr)
{
const quvi_word status = quvi_loword(param);
const quvi_word type = quvi_hiword(param);
#ifdef HAVE_LIBQUVI_0_9
status_callback_pt9(status, type, ptr);
#else
status_callback_pt4(status, type, ptr);
#endif
cc::log << std::flush;
return QUVI_OK;
}
static void print_retrying(const int retry,
const int max_retries,
const int retry_wait)
{
if (retry > 0)
{
cc::log
<< "Retrying "
<< retry
<< " of "
<< max_retries
<< " ... "
<< std::flush;
cc::wait(retry_wait);
}
}
static void print_checking(const int i, const int n)
{
if (n > 1) cc::log << "(" << i << " of " << n << ") ";
cc::log << "Checking ... " << std::flush;
}
static void print_quvi_error(const quvi::error& e)
{
cc::log << "libquvi: error: " << e.what() << std::endl;
}
namespace po = boost::program_options;
typedef std::vector<std::string> vst;
static application::exit_status
print_streams(const quvi::query& query, const quvi::options &qopts,
const vst& input_urls)
{
const size_t n = input_urls.size();
size_t i = 0;
foreach (const std::string& url, input_urls)
{
try
{
print_checking(++i,n);
query.setup_curl();
const std::string r = query.streams(url, qopts);
print_done();
if (cc::opts.flags.print_streams)
{
vst a;
boost::split(a, r, boost::is_any_of("|,"));
foreach (const std::string s, a)
{
cc::log << s << "\n";
}
}
else
cc::log << std::setw(10) << r << " : " << url << std::endl;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
return application::error;
}
}
return application::ok;
}
static void read_from(std::istream& is, vst& dst)
{
std::string s;
char ch = 0;
while (is.get(ch))
s += ch;
std::istringstream iss(s);
std::copy(
std::istream_iterator<std::string >(iss),
std::istream_iterator<std::string >(),
std::back_inserter<vst>(dst)
);
}
static bool is_url(const std::string& s)
{
return strstr(const_cast<char*>(s.c_str()), "://") != NULL;
}
static void parse_prefer_format(const std::string& url, std::string& fmt,
const po::variables_map& map)
{
vst vb, va = map["prefer-format"].as<vst>();
foreach (const std::string s, va)
{
boost::split(vb, s, boost::is_any_of(":"));
if (vb.size() == 2)
{
// vb[0] = pattern
// vb[1] = format
if (cc::re::grep(vb[0], url))
{
fmt = vb[1];
return;
}
}
vb.clear();
}
}
static void set_stream(const std::string& url, quvi::options& qopts,
const po::variables_map& map)
{
std::string s = "default";
if (map.count("stream"))
s = map["stream"].as<std::string>();
else
{
if (map.count("prefer-format"))
parse_prefer_format(url, s, map);
}
qopts.stream = s;
}
static const char copyr[] =
"\n\nCopyright (C) 2010-2013 Toni Gundogdu <[email protected]>\n"
"cclive comes with ABSOLUTELY NO WARRANTY. You may redistribute copies of\n"
"cclive under the terms of the GNU Affero General Public License version\n"
"3 or later. For more information, see "
"<http://www.gnu.org/licenses/agpl.html>.\n\n"
"To contact the developers, please mail to "
"<[email protected]>";
static const application::exit_status print_version()
{
std::cout
<< "cclive "
#ifdef VN
<< VN
#else
<< PACKAGE_VERSION
#endif
<< "\n built on "
<< BUILD_TIME
<< " for " << CANONICAL_TARGET
<< "\n libquvi "
<< quvi::version()
<< "\n libquvi-scripts "
<< quvi_version(QUVI_VERSION_SCRIPTS)
<< copyr
<< std::endl;
return application::ok;
}
application::exit_status application::exec(int argc, char **argv)
{
try
{
opts.exec(argc,argv);
}
catch(const std::exception& e)
{
std::clog << "error: " << e.what() << std::endl;
return application::error;
}
const po::variables_map map = cc::opts.map();
// Dump and terminate options.
if (opts.flags.help)
{
std::cout << opts << std::flush;
return application::ok;
}
else if (opts.flags.print_config)
{
opts.dump();
return application::ok;
}
else if (opts.flags.version)
return print_version();
// --support
quvi::query query; // Throws quvi::error caught in main.cpp
if (opts.flags.support)
{
std::cout << quvi::support_to_s(query.support()) << std::flush;
return application::ok;
}
// Parse input.
cc::input ci;
const vst input_urls = cc::input().urls();
if (input_urls.size() ==0)
{
std::clog << "error: no input URL" << std::endl;
return application::error;
}
// Set up quvi.
quvi::options qopts;
qopts.useragent = map["agent"].as<std::string>(); /* libquvi 0.9+ */
qopts.resolve = ! opts.flags.no_resolve;
qopts.statusfunc = status_callback;
// Omit flag.
bool omit = opts.flags.quiet;
// Go to background.
#ifdef HAVE_FORK
const bool background_given = opts.flags.background;
if (background_given)
{
// (Boost) Throws std::runtime_error if fails.
cc::go_background(map["log-file"].as<std::string>(), omit);
}
#endif
// Omit std output. Note that --background flips this above.
cc::log.push(cc::omit_sink(omit));
cc::log.setf(std::ios::fixed);
// Print streams.
if (opts.flags.print_streams)
return print_streams(query, qopts, input_urls);
#if defined (HAVE_FORK) && defined (HAVE_GETPID)
if (background_given)
{
cc::log
<< "Running in background (pid: "
<< static_cast<long>(getpid())
<< ")."
<< std::endl;
}
#endif
// For each input URL.
const size_t n = input_urls.size();
size_t i = 0;
const int max_retries = map["max-retries"].as<int>();
const int retry_wait = map["retry-wait"].as<int>();
exit_status es = ok;
foreach(const std::string& url, input_urls)
{
++i;
try
{
int retry = 0;
while (retry <= max_retries)
{
print_retrying(retry, max_retries, retry_wait);
++retry;
print_checking(i, n);
quvi::media m;
try
{
set_stream(url, qopts, map);
_curl = query.setup_curl();
m = query.parse(url, qopts);
}
catch(const quvi::error& e)
{
if (e.cannot_retry())
throw e;
else
print_quvi_error(e);
}
cc::get(m, _curl);
break; // Stop retrying.
}
es = ok;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
es = application::error;
}
catch(const std::runtime_error& e)
{
cc::log << "error: " << e.what() << std::endl;
es = application::error;
}
}
return es;
}
} // namespace cc
// vim: set ts=2 sw=2 tw=72 expandtab:
<|endoftext|>
|
<commit_before>//
// main.cpp
// CS372Spring2015Examples
//
// Created by Chris Hartman on 1/26/15.
// Copyright (c) 2015 Chris Hartman. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
<commit_msg>Added example of foo taking int reference.<commit_after>//
// main.cpp
// CS372Spring2015Examples
//
// Created by Chris Hartman on 1/26/15.
// Copyright (c) 2015 Chris Hartman. All rights reserved.
//
#include <iostream>
using std::cout;
using std::endl;
template <typename T>
void foo(T& i)
{
i++;
}
int main() {
int x=5;
cout << x << endl;
foo(x);
cout << "Now x is " << x << endl;
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Split overly long line into multiple lines.<commit_after><|endoftext|>
|
<commit_before>#ifndef PI
#define PI 3.14159265359f
#endif
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#ifndef RADIANS_TO_DEGREES
#define RADIANS_TO_DEGREES(x) (x * 180.0f / PI)
#endif
#include "universe.hpp"
#include "scene.hpp"
#include "ground_level.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/config/setting.hpp"
#include "code/ylikuutio/config/setting_master.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include "code/ylikuutio/common/global_variables.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this.
namespace ontology
{
Universe::Universe()
{
// constructor.
this->world_radius = NAN; // world radius is NAN as long it doesn't get `set` by `SettingMaster`.
this->setting_master_pointer = nullptr;
}
Universe::~Universe()
{
// destructor.
std::cout << "This world will be destroyed.\n";
// destroy all scenes of this world.
std::cout << "All scenes of this world will be destroyed.\n";
hierarchy::delete_children<ontology::Scene*>(this->scene_pointer_vector);
std::cout << "The setting master of this universe will be destroyed.\n";
delete this->setting_master_pointer;
}
void Universe::render()
{
this->compute_matrices_from_inputs();
// render Universe by calling `render()` function of each Scene.
ontology::render_children<ontology::Scene*>(this->scene_pointer_vector);
}
void Universe::set_background_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
this->background_red = red;
this->background_green = green;
this->background_blue = blue;
this->background_alpha = alpha;
glClearColor(this->background_red, this->background_green, this->background_blue, this->background_alpha);
}
void Universe::set_scene_pointer(uint32_t childID, ontology::Scene* child_pointer)
{
hierarchy::set_child_pointer(childID, child_pointer, this->scene_pointer_vector, this->free_sceneID_queue);
}
void Universe::set_terrain_species_pointer(ontology::Species* terrain_species_pointer)
{
this->terrain_species_pointer = terrain_species_pointer;
}
void Universe::compute_matrices_from_inputs()
{
if (!is_flight_mode_in_use)
{
fallSpeed += gravity;
position.y -= fallSpeed;
}
GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead.
// adjust position according to the ground.
if (!is_flight_mode_in_use)
{
if (this->terrain_species_pointer != nullptr)
{
GLfloat ground_y = ontology::get_floor_level(static_cast<ontology::Species*>(this->terrain_species_pointer), position);
if (!std::isnan(ground_y) && position.y < ground_y)
{
position.y = ground_y;
fallSpeed = 0.0f;
}
}
}
if (testing_spherical_world_in_use)
{
// compute spherical coordinates.
spherical_position.rho = sqrt((position.x * position.x) + (position.y * position.y) + (position.z * position.z));
spherical_position.theta = RADIANS_TO_DEGREES(atan2(sqrt((position.x * position.x) + (position.y * position.y)), position.z));
spherical_position.phi = RADIANS_TO_DEGREES(atan2(position.y, position.x));
}
camera_position = position;
camera_position.y += 2.0f;
// Projection matrix : 45° Field of View, aspect ratio, display range : 0.1 unit <-> 100 units
ProjectionMatrix = glm::perspective(FoV, aspect_ratio, 0.001f, 5000.0f + 2.0f * static_cast<GLfloat>(this->world_radius));
// Camera matrix
ViewMatrix = glm::lookAt(
camera_position, // Camera is here
camera_position+direction, // and looks here : at the same position, plus "direction"
up // Head is up (set to 0,-1,0 to look upside-down)
);
}
}
<commit_msg>Edited whitespace.<commit_after>#ifndef PI
#define PI 3.14159265359f
#endif
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#ifndef RADIANS_TO_DEGREES
#define RADIANS_TO_DEGREES(x) (x * 180.0f / PI)
#endif
#include "universe.hpp"
#include "scene.hpp"
#include "ground_level.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/config/setting.hpp"
#include "code/ylikuutio/config/setting_master.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include "code/ylikuutio/common/global_variables.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this.
namespace ontology
{
Universe::Universe()
{
// constructor.
this->world_radius = NAN; // world radius is NAN as long it doesn't get `set` by `SettingMaster`.
this->setting_master_pointer = nullptr;
}
Universe::~Universe()
{
// destructor.
std::cout << "This world will be destroyed.\n";
// destroy all scenes of this world.
std::cout << "All scenes of this world will be destroyed.\n";
hierarchy::delete_children<ontology::Scene*>(this->scene_pointer_vector);
std::cout << "The setting master of this universe will be destroyed.\n";
delete this->setting_master_pointer;
}
void Universe::render()
{
this->compute_matrices_from_inputs();
// render Universe by calling `render()` function of each Scene.
ontology::render_children<ontology::Scene*>(this->scene_pointer_vector);
}
void Universe::set_background_color(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
this->background_red = red;
this->background_green = green;
this->background_blue = blue;
this->background_alpha = alpha;
glClearColor(this->background_red, this->background_green, this->background_blue, this->background_alpha);
}
void Universe::set_scene_pointer(uint32_t childID, ontology::Scene* child_pointer)
{
hierarchy::set_child_pointer(childID, child_pointer, this->scene_pointer_vector, this->free_sceneID_queue);
}
void Universe::set_terrain_species_pointer(ontology::Species* terrain_species_pointer)
{
this->terrain_species_pointer = terrain_species_pointer;
}
void Universe::compute_matrices_from_inputs()
{
if (!is_flight_mode_in_use)
{
fallSpeed += gravity;
position.y -= fallSpeed;
}
GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead.
// adjust position according to the ground.
if (!is_flight_mode_in_use)
{
if (this->terrain_species_pointer != nullptr)
{
GLfloat ground_y = ontology::get_floor_level(static_cast<ontology::Species*>(this->terrain_species_pointer), position);
if (!std::isnan(ground_y) && position.y < ground_y)
{
position.y = ground_y;
fallSpeed = 0.0f;
}
}
}
if (testing_spherical_world_in_use)
{
// compute spherical coordinates.
spherical_position.rho = sqrt((position.x * position.x) + (position.y * position.y) + (position.z * position.z));
spherical_position.theta = RADIANS_TO_DEGREES(atan2(sqrt((position.x * position.x) + (position.y * position.y)), position.z));
spherical_position.phi = RADIANS_TO_DEGREES(atan2(position.y, position.x));
}
camera_position = position;
camera_position.y += 2.0f;
// Projection matrix : 45° Field of View, aspect ratio, display range : 0.1 unit <-> 100 units
ProjectionMatrix = glm::perspective(FoV, aspect_ratio, 0.001f, 5000.0f + 2.0f * static_cast<GLfloat>(this->world_radius));
// Camera matrix
ViewMatrix = glm::lookAt(
camera_position, // Camera is here
camera_position + direction, // and looks here : at the same position, plus "direction"
up // Head is up (set to 0,-1,0 to look upside-down)
);
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
#include <cstdio>
#include <cstdlib>
using namespace std;
// nSwap == nNiXuNumber
Class BuddleSortWithReversals
{
public:
int getCurNiXuNumber(vector<int> A)
{
int n = A.size();
int cnt = 0;
for (int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (A[i] > A[j])
{
cnt++;
}
}
}
return cnt;
}
int getMaxNixuNumber(vector<int> A)
{
int n = A.size();
return n * (n - 1) / 2;
}
int getMinSwaps(vector<int> A, int K)
{
}
};
<commit_msg>advanced DP, refer to editorial, good<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
#include <cstdio>
#include <cstdlib>
using namespace std;
// nSwap == nNiXuNumber
class BubbleSortWithReversals
{
public:
// return the number of nixu with index >= x
int getCurNiXuNumber(vector<int> A, int x)
{
int n = A.size();
int cnt = 0;
for (int i = x; i < n; ++i)
{
for (int j = 0; j < i; ++j)
{
if (A[j] > A[i])
{
cnt++;
}
}
}
return cnt;
}
// DP solution:
// Define: f(x, k) = the number of nixu with indices i >= x that can reverse
// at most k subarray without overlap, thea number of xinu at index i,
// is the number of index j with j < i && A[j] > A{i]
//
// Then the f(0, K) is the answer of original problem
//
// Base Case: f(n, k) = 0 with k = 0, 1, 2, ... MAX_K;
// Recursive relationship:
// Case 1: A[x] is not in the reversed subarray, which means A[x] stays in index
// x after the most k reverses of subarray, Note that the order of elems
// A[j] with j < x do not affect the the number of Nixu at index x
// So in this case
// f(x, k) = The number of nixu at index x + f(x + 1, k)
// Case 2: A[x] is in the reversed subarray, we only need to consider the reversed // subarray (A[x], A[x+1], ..., A[y-1], A[y]), cause if the reversing
// start before index x such as (A[a], A[b], A[c], A[x], ...), then when
// x = a, it equals exactly the situation of current time
// So in this Case:
// We first revere (A[x], A[x+1], ..., A[y-1], A[y]) to obtain
// (A[0],...A[x-1], A[y], A[y-1], ..., A[x+1], A[x])
// Then we caculate The number of nixu at index x + f(y+1, k-1)
// f(x, k) = the number of nixu at x + f(y + 1, k - 1);
// Compare case 1 and case 2 to get the minimum
int getMinSwaps(vector<int> A, int K)
{
int n = A.size();
int f[MAX_K][MAX_K] = {0};
// init
for (int k = 0; k < MAX_K; ++k) f[n][k] = 0;
//
for (int x = n - 1; x >= 0; --x)
{
for (int k = 0; k <= K; ++k)
{
// Case 1: x not in the reversed subarray
vector<int> B1(A.begin(), A.begin() + x + 1);
f[x][k] = getCurNiXuNumber(B1, x) + f[x+1][k];
// Case 2: x in the reversed subarray
if (k >= 1)
{
for (int y = x + 1; y < n; ++y)
{
vector<int> B2(A.begin(), A.begin() + y + 1);
reverse(B2.begin() + x, B2.begin() + y + 1);
f[x][k] = min(f[x][k],
getCurNiXuNumber(B2, x) + f[y+1][k-1]);
}
}
}
}
return f[0][K];
}
public:
static const int MAX_K = 51;
};
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medickal and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ 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 "SampleApp.h"
#include <QmitkStdMultiWidget.h>
#include <QmitkSelectableGLWidget.h>
#include <QmitkCommonFunctionality.h>
#include <mitkStatusBar.h>
#include <QmitkFunctionality.h>
#include <QmitkFunctionalityFactory.h>
#include <QmitkFctMediator.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
#include <QmitkControlsLeftFctLayoutTemplate.h>
#include <qlayout.h>
void RegisterFunctionalities();
SampleApp::SampleApp( QWidget* parent, const char* name, WFlags fl, const char* testingParameter ):
QmitkMainTemplate( parent, name, fl ), m_ControlsLeft ( false ), m_TestingParameter(testingParameter)
{
RegisterFunctionalities();
this->setCaption("MITK Application");
std::cout << "Instantiating new SampleApp..." << std::endl;
QmitkMainTemplate::Initialize();
parseCommandLine();
connect (this, SIGNAL(ShowWidgetPlanesToggled(bool)), this, SLOT(SetWidgetPlanesEnabled(bool)));
resize(1024,768);
}
/*
* Destroys the object and frees any allocated resources
*/
SampleApp::~SampleApp()
{
// no need to delete child widgets, Qt does it all for us
}
void SampleApp::InitializeFunctionality()
{
m_MultiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
//create and add functionalities. Functionalities are also invisible objects, which can be asked to
//create their different parts (main widget, control widget, toolbutton for selection).
mitk::DataTreePreOrderIterator iterator(m_Tree);
QmitkFunctionalityFactory& qff = QmitkFunctionalityFactory::GetInstance();
for (std::list<QmitkFunctionalityFactory::CreateFunctionalityPtr>::const_iterator it = qff.GetCreateFunctionalityPtrList().begin() ; it != qff.GetCreateFunctionalityPtrList().end(); it++) {
QmitkFunctionality* functionalityInstance = (*it)(qfm,m_MultiWidget,&iterator);
if (!m_TestingParameter) {
qfm->AddFunctionality(functionalityInstance);
} else if (strcmp(m_TestingParameter,functionalityInstance->name()) == 0) {
std::cout << "adding selected " << functionalityInstance->name() << std::endl;
qfm->AddFunctionality(functionalityInstance);
} else {
std::cout << "rejecting functionality " << functionalityInstance->name() << std::endl;
}
}
mitk::StatusBar::GetInstance()->DisplayText("Functionalities added",3000);
}
void SampleApp::InitializeQfm()
{
if (m_ControlsLeft) {
//create an QmitkFctMediator. This is an invisible object that controls, manages and mediates functionalities
qfm=new QmitkFctMediator(this);
//create an QmitkButtonFctLayoutTemplate. This is an simple example for an layout of the different widgets, of which
//a functionality and the management consists: the main widget, the control widget and a menu for selecting the
//active functionality.
QmitkControlsLeftFctLayoutTemplate* layoutTemplate=new QmitkControlsLeftFctLayoutTemplate(this, "LayoutTemplate");
setCentralWidget(layoutTemplate);
//let the QmitkFctMediator know about the layout. This includes the toolbar and the layoutTemplate.
qfm->Initialize(this);
}
else
{
QmitkMainTemplate::InitializeQfm();
}
}
void SampleApp::SetWidgetPlanesEnabled(bool enable)
{
CommonFunctionality::SetWidgetPlanesEnabled(m_Tree, enable);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
<commit_msg>comment<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medickal and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ 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 "SampleApp.h"
#include <QmitkStdMultiWidget.h>
#include <QmitkSelectableGLWidget.h>
#include <QmitkCommonFunctionality.h>
#include <mitkStatusBar.h>
#include <QmitkFunctionality.h>
#include <QmitkFunctionalityFactory.h>
#include <QmitkFctMediator.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
#include <QmitkControlsLeftFctLayoutTemplate.h>
#include <qlayout.h>
void RegisterFunctionalities();
SampleApp::SampleApp( QWidget* parent, const char* name, WFlags fl, const char* testingParameter ):
QmitkMainTemplate( parent, name, fl ), m_ControlsLeft ( false ), m_TestingParameter(testingParameter)
{
RegisterFunctionalities();
this->setCaption("MITK Application");
std::cout << "Instantiating new SampleApp..." << std::endl;
QmitkMainTemplate::Initialize();
parseCommandLine();
// TODO: Move this slot to MainApp! Or find a good reason to keep it here
connect (this, SIGNAL(ShowWidgetPlanesToggled(bool)), this, SLOT(SetWidgetPlanesEnabled(bool)));
resize(1024,768);
}
/*
* Destroys the object and frees any allocated resources
*/
SampleApp::~SampleApp()
{
// no need to delete child widgets, Qt does it all for us
}
void SampleApp::InitializeFunctionality()
{
m_MultiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
//create and add functionalities. Functionalities are also invisible objects, which can be asked to
//create their different parts (main widget, control widget, toolbutton for selection).
mitk::DataTreePreOrderIterator iterator(m_Tree);
QmitkFunctionalityFactory& qff = QmitkFunctionalityFactory::GetInstance();
for (std::list<QmitkFunctionalityFactory::CreateFunctionalityPtr>::const_iterator it = qff.GetCreateFunctionalityPtrList().begin() ; it != qff.GetCreateFunctionalityPtrList().end(); it++) {
QmitkFunctionality* functionalityInstance = (*it)(qfm,m_MultiWidget,&iterator);
if (!m_TestingParameter) {
qfm->AddFunctionality(functionalityInstance);
} else if (strcmp(m_TestingParameter,functionalityInstance->name()) == 0) {
std::cout << "adding selected " << functionalityInstance->name() << std::endl;
qfm->AddFunctionality(functionalityInstance);
} else {
std::cout << "rejecting functionality " << functionalityInstance->name() << std::endl;
}
}
mitk::StatusBar::GetInstance()->DisplayText("Functionalities added",3000);
}
void SampleApp::InitializeQfm()
{
if (m_ControlsLeft) {
//create an QmitkFctMediator. This is an invisible object that controls, manages and mediates functionalities
qfm=new QmitkFctMediator(this);
//create an QmitkButtonFctLayoutTemplate. This is an simple example for an layout of the different widgets, of which
//a functionality and the management consists: the main widget, the control widget and a menu for selecting the
//active functionality.
QmitkControlsLeftFctLayoutTemplate* layoutTemplate=new QmitkControlsLeftFctLayoutTemplate(this, "LayoutTemplate");
setCentralWidget(layoutTemplate);
//let the QmitkFctMediator know about the layout. This includes the toolbar and the layoutTemplate.
qfm->Initialize(this);
}
else
{
QmitkMainTemplate::InitializeQfm();
}
}
void SampleApp::SetWidgetPlanesEnabled(bool enable)
{
CommonFunctionality::SetWidgetPlanesEnabled(m_Tree, enable);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInteractorObserver.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkInteractorObserver.h"
#include "vtkCallbackCommand.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
vtkCxxRevisionMacro(vtkInteractorObserver, "1.19");
vtkInteractorObserver::vtkInteractorObserver()
{
this->Enabled = 0;
this->Interactor = NULL;
this->EventCallbackCommand = vtkCallbackCommand::New();
this->EventCallbackCommand->SetClientData(this);
//subclass has to invoke SetCallback()
this->KeyPressCallbackCommand = vtkCallbackCommand::New();
this->KeyPressCallbackCommand->SetClientData(this);
this->KeyPressCallbackCommand->SetCallback(vtkInteractorObserver::ProcessEvents);
this->CurrentRenderer = NULL;
this->Priority = 0.0;
this->KeyPressActivation = 1;
this->KeyPressActivationValue = 'i';
}
vtkInteractorObserver::~vtkInteractorObserver()
{
this->EventCallbackCommand->Delete();
this->KeyPressCallbackCommand->Delete();
}
// This adds the keypress event observer and the delete event observer
void vtkInteractorObserver::SetInteractor(vtkRenderWindowInteractor* i)
{
if (i == this->Interactor)
{
return;
}
// if we already have an Interactor then stop observing it
if (this->Interactor)
{
this->SetEnabled(0); //disable the old interactor
this->Interactor->RemoveObserver(this->KeyPressCallbackCommand);
}
this->Interactor = i;
// add observers for each of the events handled in ProcessEvents
if (i)
{
i->AddObserver(vtkCommand::CharEvent,
this->KeyPressCallbackCommand,
this->Priority);
i->AddObserver(vtkCommand::DeleteEvent,
this->KeyPressCallbackCommand,
this->Priority);
}
this->Modified();
}
void vtkInteractorObserver::ProcessEvents(vtkObject* vtkNotUsed(object),
unsigned long event,
void* clientdata,
void* vtkNotUsed(calldata))
{
vtkInteractorObserver* self
= reinterpret_cast<vtkInteractorObserver *>( clientdata );
//look for char and delete events
switch(event)
{
case vtkCommand::CharEvent:
self->OnChar();
break;
case vtkCommand::DeleteEvent:
self->Interactor = NULL; //its going bye bye
self->Enabled = 0;
break;
}
}
//----------------------------------------------------------------------------
void vtkInteractorObserver::StartInteraction()
{
this->Interactor->GetRenderWindow()->SetDesiredUpdateRate(this->Interactor->GetDesiredUpdateRate());
}
//----------------------------------------------------------------------------
void vtkInteractorObserver::EndInteraction()
{
this->Interactor->GetRenderWindow()->SetDesiredUpdateRate(this->Interactor->GetStillUpdateRate());
}
//----------------------------------------------------------------------------
// Description:
// Transform from display to world coordinates.
// WorldPt has to be allocated as 4 vector
void vtkInteractorObserver::ComputeDisplayToWorld(double x,
double y,
double z,
double worldPt[4])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetDisplayPoint(x, y, z);
this->CurrentRenderer->DisplayToWorld();
this->CurrentRenderer->GetWorldPoint(worldPt);
if (worldPt[3])
{
worldPt[0] /= worldPt[3];
worldPt[1] /= worldPt[3];
worldPt[2] /= worldPt[3];
worldPt[3] = 1.0;
}
}
void vtkInteractorObserver::ComputeDisplayToWorld(double x,
double y,
double z,
float worldPt[4])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetDisplayPoint(x, y, z);
this->CurrentRenderer->DisplayToWorld();
this->CurrentRenderer->GetWorldPoint(worldPt);
if (worldPt[3])
{
worldPt[0] /= worldPt[3];
worldPt[1] /= worldPt[3];
worldPt[2] /= worldPt[3];
worldPt[3] = 1.0;
}
}
// Description:
// Transform from world to display coordinates.
// displayPt has to be allocated as 3 vector
void vtkInteractorObserver::ComputeWorldToDisplay(double x,
double y,
double z,
double displayPt[3])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetWorldPoint(x, y, z, 1.0);
this->CurrentRenderer->WorldToDisplay();
this->CurrentRenderer->GetDisplayPoint(displayPt);
}
// Description:
// transform from world to display coordinates.
// displayPt has to be allocated as 3 vector
void vtkInteractorObserver::ComputeWorldToDisplay(double x,
double y,
double z,
float displayPt[3])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetWorldPoint(x, y, z, 1.0);
this->CurrentRenderer->WorldToDisplay();
this->CurrentRenderer->GetDisplayPoint(displayPt);
}
void vtkInteractorObserver::OnChar()
{
// catch additional keycodes otherwise
if ( this->KeyPressActivation )
{
if (this->Interactor->GetKeyCode() == this->KeyPressActivationValue )
{
if ( !this->Enabled )
{
this->On();
}
else
{
this->Off();
}
this->KeyPressCallbackCommand->SetAbortFlag(1);
}
}//if activation enabled
}
void vtkInteractorObserver::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Enabled: " << this->Enabled << "\n";
os << indent << "Priority: " << this->Priority << "\n";
os << indent << "Interactor: " << this->Interactor << "\n";
os << indent << "Key Press Activation: "
<< (this->KeyPressActivation ? "On" : "Off") << "\n";
os << indent << "Key Press Activation Value: "
<< this->KeyPressActivationValue << "\n";
}
<commit_msg>ERR: Fixed Purify FMW (free memory write)<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInteractorObserver.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkInteractorObserver.h"
#include "vtkCallbackCommand.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
vtkCxxRevisionMacro(vtkInteractorObserver, "1.20");
vtkInteractorObserver::vtkInteractorObserver()
{
this->Enabled = 0;
this->Interactor = NULL;
this->EventCallbackCommand = vtkCallbackCommand::New();
this->EventCallbackCommand->SetClientData(this);
//subclass has to invoke SetCallback()
this->KeyPressCallbackCommand = vtkCallbackCommand::New();
this->KeyPressCallbackCommand->SetClientData(this);
this->KeyPressCallbackCommand->SetCallback(vtkInteractorObserver::ProcessEvents);
this->CurrentRenderer = NULL;
this->Priority = 0.0;
this->KeyPressActivation = 1;
this->KeyPressActivationValue = 'i';
}
vtkInteractorObserver::~vtkInteractorObserver()
{
this->EventCallbackCommand->Delete();
this->KeyPressCallbackCommand->Delete();
}
// This adds the keypress event observer and the delete event observer
void vtkInteractorObserver::SetInteractor(vtkRenderWindowInteractor* i)
{
if (i == this->Interactor)
{
return;
}
// if we already have an Interactor then stop observing it
if (this->Interactor)
{
this->SetEnabled(0); //disable the old interactor
this->Interactor->RemoveObserver(this->KeyPressCallbackCommand);
}
this->Interactor = i;
// add observers for each of the events handled in ProcessEvents
if (i)
{
i->AddObserver(vtkCommand::CharEvent,
this->KeyPressCallbackCommand,
this->Priority);
i->AddObserver(vtkCommand::DeleteEvent,
this->KeyPressCallbackCommand,
this->Priority);
}
this->Modified();
}
void vtkInteractorObserver::ProcessEvents(vtkObject* vtkNotUsed(object),
unsigned long event,
void* clientdata,
void* vtkNotUsed(calldata))
{
vtkInteractorObserver* self
= reinterpret_cast<vtkInteractorObserver *>( clientdata );
//look for char and delete events
switch(event)
{
case vtkCommand::CharEvent:
self->OnChar();
break;
case vtkCommand::DeleteEvent:
//self->Interactor = NULL; //commented out, can't write to a
//self->Enabled = 0; //deleted object
break;
}
}
//----------------------------------------------------------------------------
void vtkInteractorObserver::StartInteraction()
{
this->Interactor->GetRenderWindow()->SetDesiredUpdateRate(this->Interactor->GetDesiredUpdateRate());
}
//----------------------------------------------------------------------------
void vtkInteractorObserver::EndInteraction()
{
this->Interactor->GetRenderWindow()->SetDesiredUpdateRate(this->Interactor->GetStillUpdateRate());
}
//----------------------------------------------------------------------------
// Description:
// Transform from display to world coordinates.
// WorldPt has to be allocated as 4 vector
void vtkInteractorObserver::ComputeDisplayToWorld(double x,
double y,
double z,
double worldPt[4])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetDisplayPoint(x, y, z);
this->CurrentRenderer->DisplayToWorld();
this->CurrentRenderer->GetWorldPoint(worldPt);
if (worldPt[3])
{
worldPt[0] /= worldPt[3];
worldPt[1] /= worldPt[3];
worldPt[2] /= worldPt[3];
worldPt[3] = 1.0;
}
}
void vtkInteractorObserver::ComputeDisplayToWorld(double x,
double y,
double z,
float worldPt[4])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetDisplayPoint(x, y, z);
this->CurrentRenderer->DisplayToWorld();
this->CurrentRenderer->GetWorldPoint(worldPt);
if (worldPt[3])
{
worldPt[0] /= worldPt[3];
worldPt[1] /= worldPt[3];
worldPt[2] /= worldPt[3];
worldPt[3] = 1.0;
}
}
// Description:
// Transform from world to display coordinates.
// displayPt has to be allocated as 3 vector
void vtkInteractorObserver::ComputeWorldToDisplay(double x,
double y,
double z,
double displayPt[3])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetWorldPoint(x, y, z, 1.0);
this->CurrentRenderer->WorldToDisplay();
this->CurrentRenderer->GetDisplayPoint(displayPt);
}
// Description:
// transform from world to display coordinates.
// displayPt has to be allocated as 3 vector
void vtkInteractorObserver::ComputeWorldToDisplay(double x,
double y,
double z,
float displayPt[3])
{
if ( !this->CurrentRenderer )
{
return;
}
this->CurrentRenderer->SetWorldPoint(x, y, z, 1.0);
this->CurrentRenderer->WorldToDisplay();
this->CurrentRenderer->GetDisplayPoint(displayPt);
}
void vtkInteractorObserver::OnChar()
{
// catch additional keycodes otherwise
if ( this->KeyPressActivation )
{
if (this->Interactor->GetKeyCode() == this->KeyPressActivationValue )
{
if ( !this->Enabled )
{
this->On();
}
else
{
this->Off();
}
this->KeyPressCallbackCommand->SetAbortFlag(1);
}
}//if activation enabled
}
void vtkInteractorObserver::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Enabled: " << this->Enabled << "\n";
os << indent << "Priority: " << this->Priority << "\n";
os << indent << "Interactor: " << this->Interactor << "\n";
os << indent << "Key Press Activation: "
<< (this->KeyPressActivation ? "On" : "Off") << "\n";
os << indent << "Key Press Activation Value: "
<< this->KeyPressActivationValue << "\n";
}
<|endoftext|>
|
<commit_before>#include "GameProcess.h"<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "GameProcess.h"
using namespace MathLib;<|endoftext|>
|
<commit_before><commit_msg>Typos in method descriptions.<commit_after><|endoftext|>
|
<commit_before>///
/// @file help.cpp
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesum.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
namespace {
const string helpMenu(
"Usage: primesum x [OPTION]...\n"
"Sum the primes below x <= 10^20 using fast implementations of the\n"
"combinatorial prime summing function.\n"
"\n"
"Options:\n"
"\n"
" -d, --deleglise_rivat Sum primes using Deleglise-Rivat algorithm\n"
" -l, --lmo Sum primes using Lagarias-Miller-Odlyzko\n"
" -s[N], --status[=N] Show computation progress 1%, 2%, 3%, ...\n"
" [N] digits after decimal point e.g. N=1, 99.9%\n"
" --test Run various correctness tests and exit\n"
" --time Print the time elapsed in seconds\n"
" -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n"
" -v, --version Print version and license information\n"
" -h, --help Print this help menu\n"
"\n"
"Advanced Deleglise-Rivat options:\n"
"\n"
" -a<N>, --alpha=<N> Tuning factor, 1 <= alpha <= x^(1/6)\n"
" --P2 Only compute the 2nd partial sieve function\n"
" --S1 Only compute the ordinary leaves\n"
" --S2_trivial Only compute the trivial special leaves\n"
" --S2_easy Only compute the easy special leaves\n"
" --S2_hard Only compute the hard special leaves\n"
"\n"
"Examples:\n"
"\n"
" primesum 1e13\n"
" primesum 1e13 --status --threads=4"
);
const string versionInfo(
"primesum " PRIMESUM_VERSION ", <https://github.com/kimwalisch/primesum>\n"
"Copyright (C) 2016 Kim Walisch\n"
"BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);
} // end namespace
namespace primesum {
void help()
{
cout << helpMenu << endl;
exit(1);
}
void version()
{
cout << versionInfo << endl;
exit(1);
}
} // namespace primesum
<commit_msg>Update help.cpp<commit_after>///
/// @file help.cpp
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesum.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
namespace {
const string helpMenu(
"Usage: primesum x [OPTION]...\n"
"Sum the primes below x <= 10^31 using fast implementations of the\n"
"combinatorial prime summing function.\n"
"\n"
"Options:\n"
"\n"
" -d, --deleglise_rivat Sum primes using Deleglise-Rivat algorithm\n"
" -l, --lmo Sum primes using Lagarias-Miller-Odlyzko\n"
" -s[N], --status[=N] Show computation progress 1%, 2%, 3%, ...\n"
" [N] digits after decimal point e.g. N=1, 99.9%\n"
" --test Run various correctness tests and exit\n"
" --time Print the time elapsed in seconds\n"
" -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n"
" -v, --version Print version and license information\n"
" -h, --help Print this help menu\n"
"\n"
"Advanced Deleglise-Rivat options:\n"
"\n"
" -a<N>, --alpha=<N> Tuning factor, 1 <= alpha <= x^(1/6)\n"
" --P2 Only compute the 2nd partial sieve function\n"
" --S1 Only compute the ordinary leaves\n"
" --S2_trivial Only compute the trivial special leaves\n"
" --S2_easy Only compute the easy special leaves\n"
" --S2_hard Only compute the hard special leaves\n"
"\n"
"Examples:\n"
"\n"
" primesum 1e13\n"
" primesum 1e13 --status --threads=4"
);
const string versionInfo(
"primesum " PRIMESUM_VERSION ", <https://github.com/kimwalisch/primesum>\n"
"Copyright (C) 2016 Kim Walisch\n"
"BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);
} // end namespace
namespace primesum {
void help()
{
cout << helpMenu << endl;
exit(1);
}
void version()
{
cout << versionInfo << endl;
exit(1);
}
} // namespace primesum
<|endoftext|>
|
<commit_before>#include "common/application_info.h"
#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"
namespace brightray {
std::string GetApplicationName() {
auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
return UTF16ToUTF8(info->product_name());
}
std::string GetApplicationVersion() {
auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr)));
return UTF16ToUTF8(info->product_version());
}
} // namespace brightray
<commit_msg>Fix cpplint errors in application_info_win.cc<commit_after>#include "common/application_info.h"
#include "base/file_version_info.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"
namespace brightray {
std::string GetApplicationName() {
auto module = GetModuleHandle(nullptr);
auto info = make_scoped_ptr(
FileVersionInfo::CreateFileVersionInfoForModule(module));
return UTF16ToUTF8(info->product_name());
}
std::string GetApplicationVersion() {
auto module = GetModuleHandle(nullptr);
auto info = make_scoped_ptr(
FileVersionInfo::CreateFileVersionInfoForModule(module));
return UTF16ToUTF8(info->product_version());
}
} // namespace brightray
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
using namespace fnord;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"http_port",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the public http server on this port",
"<port>");
flags.defineFlag(
"report_path",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"report path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
WhitelistVFS vfs;
/* start http server */
fnord::thread::EventLoop ev;
fnord::http::HTTPRouter http_router;
fnord::http::HTTPServer http_server(&http_router, &ev);
http_server.listen(flags.getInt("http_port"));
/* sstable servlet */
sstable::SSTableServlet sstable_servlet("/sstable", &vfs);
http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);
/* add all files to whitelist vfs */
auto report_path = flags.getString("report_path");
FileUtil::ls(report_path, [&vfs, &report_path] (const String& file) -> bool {
vfs.registerFile(file, FileUtil::joinPaths(report_path, file));
fnord::logInfo("cm.reportserver", "[VFS] Adding file: $0", file);
return true;
});
ev.run();
return 0;
}
<commit_msg>show real file sizes in downloads view<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-http/VFSFileServlet.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
using namespace fnord;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"http_port",
fnord::cli::FlagParser::T_INTEGER,
false,
NULL,
"8000",
"Start the public http server on this port",
"<port>");
flags.defineFlag(
"report_path",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"report path",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
WhitelistVFS vfs;
/* start http server */
fnord::thread::EventLoop ev;
fnord::http::HTTPRouter http_router;
fnord::http::HTTPServer http_server(&http_router, &ev);
http_server.listen(flags.getInt("http_port"));
/* sstable servlet */
sstable::SSTableServlet sstable_servlet("/sstable", &vfs);
http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);
/* file servlet */
http::VFSFileServlet file_servlet("/file", &vfs);
http_router.addRouteByPrefixMatch("/file", &file_servlet);
/* add all files to whitelist vfs */
auto report_path = flags.getString("report_path");
FileUtil::ls(report_path, [&vfs, &report_path] (const String& file) -> bool {
vfs.registerFile(file, FileUtil::joinPaths(report_path, file));
fnord::logInfo("cm.reportserver", "[VFS] Adding file: $0", file);
return true;
});
ev.run();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Part of Scallop Transcript Assembler
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/
#include <cstdio>
#include <cassert>
#include <sstream>
#include "config.h"
#include "gtf.h"
#include "genome.h"
#include "assembler.h"
#include "scallop.h"
#include "sgraph_compare.h"
#include "super_graph.h"
#include "filter.h"
assembler::assembler()
{
sfn = sam_open(input_file.c_str(), "r");
hdr = sam_hdr_read(sfn);
b1t = bam_init1();
index = 0;
terminate = false;
qlen = 0;
qcnt = 0;
}
assembler::~assembler()
{
bam_destroy1(b1t);
bam_hdr_destroy(hdr);
sam_close(sfn);
}
int assembler::assemble()
{
while(sam_read1(sfn, hdr, b1t) >= 0)
{
if(terminate == true) return 0;
bam1_core_t &p = b1t->core;
if((p.flag & 0x4) >= 1) continue; // read is not mapped
if((p.flag & 0x100) >= 1 && use_second_alignment == false) continue; // secondary alignment
if(p.n_cigar > max_num_cigar) continue; // ignore hits with more than max-num-cigar types
if(p.qual < min_mapping_quality) continue; // ignore hits with small quality
if(p.n_cigar < 1) continue; // should never happen
hit ht(b1t);
ht.set_tags(b1t);
ht.set_strand();
ht.build_splice_positions();
//ht.print();
//if(ht.nh >= 2 && p.qual < min_mapping_quality) continue;
//if(ht.nm > max_edit_distance) continue;
qlen += ht.qlen;
qcnt += 1;
// truncate
if(ht.tid != bb1.tid || ht.pos > bb1.rpos + min_bundle_gap)
{
pool.push_back(bb1);
bb1.clear();
}
if(ht.tid != bb2.tid || ht.pos > bb2.rpos + min_bundle_gap)
{
pool.push_back(bb2);
bb2.clear();
}
// process
process(batch_bundle_size);
//printf("read strand = %c, xs = %c, ts = %c\n", ht.strand, ht.xs, ht.ts);
// add hit
if(uniquely_mapped_only == true && ht.nh != 1) continue;
if(library_type != UNSTRANDED && ht.strand == '+' && ht.xs == '-') continue;
if(library_type != UNSTRANDED && ht.strand == '-' && ht.xs == '+') continue;
//if(library_type != UNSTRANDED && ht.strand == '.' && ht.xs != '.') ht.strand = ht.xs;
if(library_type != UNSTRANDED && ht.strand == '.' && ht.xs != '.' && (ht.flag & 0x8) >= 1) ht.strand = ht.xs;
if(library_type != UNSTRANDED && ht.strand == '+') bb1.add_hit(ht);
if(library_type != UNSTRANDED && ht.strand == '-') bb2.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '.') bb1.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '.') bb2.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '+') bb1.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '-') bb2.add_hit(ht);
}
pool.push_back(bb1);
pool.push_back(bb2);
process(0);
assign_RPKM();
filter ft(trsts);
ft.merge_single_exon_transcripts();
trsts = ft.trs;
write();
return 0;
}
int assembler::process(int n)
{
if(pool.size() < n) return 0;
for(int i = 0; i < pool.size(); i++)
{
bundle_base &bb = pool[i];
//printf("bundle %d has %lu reads\n", i, bb.hits.size());
if(bb.hits.size() < min_num_hits_in_bundle) continue;
if(bb.tid < 0) continue;
char buf[1024];
strcpy(buf, hdr->target_name[bb.tid]);
bundle bd(bb);
bd.chrm = string(buf);
bd.build();
bd.print(index);
//if(verbose >= 1) bd.print(index);
assemble(bd.gr, bd.hs);
index++;
}
pool.clear();
return 0;
}
int assembler::assemble(const splice_graph &gr0, const hyper_set &hs0)
{
super_graph sg(gr0, hs0);
sg.build();
vector<transcript> gv;
for(int k = 0; k < sg.subs.size(); k++)
{
string gid = "gene." + tostring(index) + "." + tostring(k);
if(fixed_gene_name != "" && gid != fixed_gene_name) continue;
if(verbose >= 2 && (k == 0 || fixed_gene_name != "")) sg.print();
splice_graph &gr = sg.subs[k];
hyper_set &hs = sg.hss[k];
gr.gid = gid;
scallop sc(gr, hs);
sc.assemble();
if(verbose >= 2)
{
printf("transcripts:\n");
for(int i = 0; i < sc.trsts.size(); i++) sc.trsts[i].write(cout);
}
filter ft(sc.trsts);
ft.join_single_exon_transcripts();
ft.filter_length_coverage();
if(ft.trs.size() >= 1) gv.insert(gv.end(), ft.trs.begin(), ft.trs.end());
if(verbose >= 2)
{
printf("transcripts after filtering:\n");
for(int i = 0; i < ft.trs.size(); i++) ft.trs[i].write(cout);
}
if(fixed_gene_name != "" && gid == fixed_gene_name) terminate = true;
if(terminate == true) return 0;
}
filter ft(gv);
ft.remove_nested_transcripts();
if(ft.trs.size() >= 1) trsts.insert(trsts.end(), ft.trs.begin(), ft.trs.end());
return 0;
}
int assembler::assign_RPKM()
{
double factor = 1e9 / qlen;
for(int i = 0; i < trsts.size(); i++)
{
trsts[i].assign_RPKM(factor);
}
return 0;
}
int assembler::write()
{
ofstream fout(output_file.c_str());
if(fout.fail()) return 0;
for(int i = 0; i < trsts.size(); i++)
{
transcript &t = trsts[i];
t.write(fout);
}
fout.close();
return 0;
}
int assembler::compare(splice_graph &gr, const string &file, const string &texfile)
{
if(file == "") return 0;
genome g(file);
if(g.genes.size() <= 0) return 0;
gtf gg(g.genes[0]);
splice_graph gt;
gg.build_splice_graph(gt);
sgraph_compare sgc(gt, gr);
sgc.compare(texfile);
return 0;
}
<commit_msg>come back<commit_after>/*
Part of Scallop Transcript Assembler
(c) 2017 by Mingfu Shao, Carl Kingsford, and Carnegie Mellon University.
See LICENSE for licensing.
*/
#include <cstdio>
#include <cassert>
#include <sstream>
#include "config.h"
#include "gtf.h"
#include "genome.h"
#include "assembler.h"
#include "scallop.h"
#include "sgraph_compare.h"
#include "super_graph.h"
#include "filter.h"
assembler::assembler()
{
sfn = sam_open(input_file.c_str(), "r");
hdr = sam_hdr_read(sfn);
b1t = bam_init1();
index = 0;
terminate = false;
qlen = 0;
qcnt = 0;
}
assembler::~assembler()
{
bam_destroy1(b1t);
bam_hdr_destroy(hdr);
sam_close(sfn);
}
int assembler::assemble()
{
while(sam_read1(sfn, hdr, b1t) >= 0)
{
if(terminate == true) return 0;
bam1_core_t &p = b1t->core;
if((p.flag & 0x4) >= 1) continue; // read is not mapped
if((p.flag & 0x100) >= 1 && use_second_alignment == false) continue; // secondary alignment
if(p.n_cigar > max_num_cigar) continue; // ignore hits with more than max-num-cigar types
if(p.qual < min_mapping_quality) continue; // ignore hits with small quality
if(p.n_cigar < 1) continue; // should never happen
hit ht(b1t);
ht.set_tags(b1t);
ht.set_strand();
ht.build_splice_positions();
//ht.print();
//if(ht.nh >= 2 && p.qual < min_mapping_quality) continue;
//if(ht.nm > max_edit_distance) continue;
qlen += ht.qlen;
qcnt += 1;
// truncate
if(ht.tid != bb1.tid || ht.pos > bb1.rpos + min_bundle_gap)
{
pool.push_back(bb1);
bb1.clear();
}
if(ht.tid != bb2.tid || ht.pos > bb2.rpos + min_bundle_gap)
{
pool.push_back(bb2);
bb2.clear();
}
// process
process(batch_bundle_size);
//printf("read strand = %c, xs = %c, ts = %c\n", ht.strand, ht.xs, ht.ts);
// add hit
if(uniquely_mapped_only == true && ht.nh != 1) continue;
if(library_type != UNSTRANDED && ht.strand == '+' && ht.xs == '-') continue;
if(library_type != UNSTRANDED && ht.strand == '-' && ht.xs == '+') continue;
if(library_type != UNSTRANDED && ht.strand == '.' && ht.xs != '.') ht.strand = ht.xs;
if(library_type != UNSTRANDED && ht.strand == '+') bb1.add_hit(ht);
if(library_type != UNSTRANDED && ht.strand == '-') bb2.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '.') bb1.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '.') bb2.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '+') bb1.add_hit(ht);
if(library_type == UNSTRANDED && ht.xs == '-') bb2.add_hit(ht);
}
pool.push_back(bb1);
pool.push_back(bb2);
process(0);
assign_RPKM();
filter ft(trsts);
ft.merge_single_exon_transcripts();
trsts = ft.trs;
write();
return 0;
}
int assembler::process(int n)
{
if(pool.size() < n) return 0;
for(int i = 0; i < pool.size(); i++)
{
bundle_base &bb = pool[i];
//printf("bundle %d has %lu reads\n", i, bb.hits.size());
if(bb.hits.size() < min_num_hits_in_bundle) continue;
if(bb.tid < 0) continue;
char buf[1024];
strcpy(buf, hdr->target_name[bb.tid]);
bundle bd(bb);
bd.chrm = string(buf);
bd.build();
bd.print(index);
//if(verbose >= 1) bd.print(index);
assemble(bd.gr, bd.hs);
index++;
}
pool.clear();
return 0;
}
int assembler::assemble(const splice_graph &gr0, const hyper_set &hs0)
{
super_graph sg(gr0, hs0);
sg.build();
vector<transcript> gv;
for(int k = 0; k < sg.subs.size(); k++)
{
string gid = "gene." + tostring(index) + "." + tostring(k);
if(fixed_gene_name != "" && gid != fixed_gene_name) continue;
if(verbose >= 2 && (k == 0 || fixed_gene_name != "")) sg.print();
splice_graph &gr = sg.subs[k];
hyper_set &hs = sg.hss[k];
gr.gid = gid;
scallop sc(gr, hs);
sc.assemble();
if(verbose >= 2)
{
printf("transcripts:\n");
for(int i = 0; i < sc.trsts.size(); i++) sc.trsts[i].write(cout);
}
filter ft(sc.trsts);
ft.join_single_exon_transcripts();
ft.filter_length_coverage();
if(ft.trs.size() >= 1) gv.insert(gv.end(), ft.trs.begin(), ft.trs.end());
if(verbose >= 2)
{
printf("transcripts after filtering:\n");
for(int i = 0; i < ft.trs.size(); i++) ft.trs[i].write(cout);
}
if(fixed_gene_name != "" && gid == fixed_gene_name) terminate = true;
if(terminate == true) return 0;
}
filter ft(gv);
ft.remove_nested_transcripts();
if(ft.trs.size() >= 1) trsts.insert(trsts.end(), ft.trs.begin(), ft.trs.end());
return 0;
}
int assembler::assign_RPKM()
{
double factor = 1e9 / qlen;
for(int i = 0; i < trsts.size(); i++)
{
trsts[i].assign_RPKM(factor);
}
return 0;
}
int assembler::write()
{
ofstream fout(output_file.c_str());
if(fout.fail()) return 0;
for(int i = 0; i < trsts.size(); i++)
{
transcript &t = trsts[i];
t.write(fout);
}
fout.close();
return 0;
}
int assembler::compare(splice_graph &gr, const string &file, const string &texfile)
{
if(file == "") return 0;
genome g(file);
if(g.genes.size() <= 0) return 0;
gtf gg(g.genes[0]);
splice_graph gt;
gg.build_splice_graph(gt);
sgraph_compare sgc(gt, gr);
sgc.compare(texfile);
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "renderer/scene/gravitationalobject.hpp"
#include "collisiondetection/collidable.hpp"
/**
* Basic brown gravitational asteroid.
*/
class Asteroid : public scene::GravitationalObject, public collisiondetection::Collidable {
public:
Asteroid(glm::vec3 initialLocation, unsigned int mass);
virtual void handleCollision(scene::SceneItem& collidee);
};<commit_msg>Add override-keyword<commit_after>#pragma once
#include "renderer/scene/gravitationalobject.hpp"
#include "collisiondetection/collidable.hpp"
/**
* Basic brown gravitational asteroid.
*/
class Asteroid : public scene::GravitationalObject, public collisiondetection::Collidable {
public:
Asteroid(glm::vec3 initialLocation, unsigned int mass);
virtual void handleCollision(scene::SceneItem& collidee) override;
};<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageViewer.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight 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 <iostream>
#include <itkImage.h>
#include <itkImageFileReader.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/fl_file_chooser.H>
#include <GLSliceView.h>
#include "ImageViewerGUI.h"
Fl_Window *form;
int usage(void)
{
std::cout << "ImageViewer" << std::endl;
std::cout << std::endl;
std::cout << "ImageViewer <Filename>" << std::endl;
std::cout << std::endl;
return 1;
}
int main(int argc, char **argv)
{
typedef itk::Image< float, 3 > ImageType;
char *fName;
if(argc > 2)
{
return usage();
}
else
if(argc == 1)
{
fName = fl_file_chooser("Pick an image file", "*.*", ".");
if(fName == NULL || strlen(fName)<1)
{
return 0;
}
}
else
if(argv[1][0] != '-')
{
fName = argv[argc-1];
}
else
{
return usage();
}
std::cout << "Loading File: " << fName << std::endl;
typedef itk::ImageFileReader< ImageType > VolumeReaderType;
VolumeReaderType::Pointer reader = VolumeReaderType::New();
reader->SetFileName(fName);
ImageType::Pointer imP;
imP = reader->GetOutput();
try
{
reader->Update();
}
catch( ... )
{
std::cout << "Problems reading file format" << std::endl;
return 1;
}
std::cout << "...Done Loading File" << std::endl;
char mainName[255];
sprintf(mainName, "metaView: %s", fName);
std::cout << std::endl;
std::cout << "For directions on interacting with the window," << std::endl;
std::cout << " type 'h' within the window" << std::endl;
form = make_window();
tkMain->label(mainName);
tkWin->SetInputImage(imP);
form->show();
tkWin->show();
tkWin->update();
Fl::run();
return 1;
}
<commit_msg>(split) ENH: Force a first redraw.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageViewer.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight 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 <iostream>
#include <itkImage.h>
#include <itkImageFileReader.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/fl_file_chooser.H>
#include <GLSliceView.h>
#include "ImageViewerGUI.h"
Fl_Window *form;
int usage(void)
{
std::cout << "ImageViewer" << std::endl;
std::cout << std::endl;
std::cout << "ImageViewer <Filename>" << std::endl;
std::cout << std::endl;
return 1;
}
int main(int argc, char **argv)
{
typedef itk::Image< float, 3 > ImageType;
char *fName;
if(argc > 2)
{
return usage();
}
else
if(argc == 1)
{
fName = fl_file_chooser("Pick an image file", "*.*", ".");
if(fName == NULL || strlen(fName)<1)
{
return 0;
}
}
else
if(argv[1][0] != '-')
{
fName = argv[argc-1];
}
else
{
return usage();
}
std::cout << "Loading File: " << fName << std::endl;
typedef itk::ImageFileReader< ImageType > VolumeReaderType;
VolumeReaderType::Pointer reader = VolumeReaderType::New();
reader->SetFileName(fName);
ImageType::Pointer imP;
imP = reader->GetOutput();
try
{
reader->Update();
}
catch( ... )
{
std::cout << "Problems reading file format" << std::endl;
return 1;
}
std::cout << "...Done Loading File" << std::endl;
char mainName[255];
sprintf(mainName, "metaView: %s", fName);
std::cout << std::endl;
std::cout << "For directions on interacting with the window," << std::endl;
std::cout << " type 'h' within the window" << std::endl;
form = make_window();
tkMain->label(mainName);
tkWin->SetInputImage(imP);
form->show();
tkWin->show();
tkWin->update();
// force a first redraw
Fl::check();
tkWin->update();
Fl::run();
return 1;
}
<|endoftext|>
|
<commit_before>// Copyright 2013 Samplecount S.L.
//
// 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.
#ifndef METHCLA_PLUGIN_HPP_INCLUDED
#define METHCLA_PLUGIN_HPP_INCLUDED
#include <methcla/log.hpp>
#include <methcla/plugin.h>
#include <oscpp/server.hpp>
#include <functional>
#include <cstring>
// NOTE: This API is unstable and subject to change!
namespace Methcla { namespace Plugin {
template <class Synth> class World
{
const Methcla_World* m_world;
public:
World(const Methcla_World* world)
: m_world(world)
{ }
double sampleRate() const
{
return methcla_world_samplerate(m_world);
}
size_t blockSize() const
{
return methcla_world_block_size(m_world);
}
Methcla_Time currentTime() const
{
return methcla_world_current_time(m_world);
}
void* alloc(size_t size) const
{
return methcla_world_alloc(m_world, size);
}
void* allocAligned(size_t alignment, size_t size) const
{
return methcla_world_alloc_aligned(m_world, alignment, size);
}
void free(void* ptr)
{
methcla_world_free(m_world, ptr);
}
void performCommand(Methcla_HostPerformFunction perform, void* data)
{
methcla_world_perform_command(m_world, perform, data);
}
LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)
{
using namespace std::placeholders;
return LogStream(std::bind(m_world->log_line, m_world, _1, _2), logLevel);
}
void synthRetain(Synth* synth) const
{
methcla_world_synth_retain(m_world, synth);
}
void synthRelease(Synth* synth) const
{
methcla_world_synth_release(m_world, synth);
}
void synthDone(Synth* synth) const
{
methcla_world_synth_done(m_world, synth);
}
};
class HostContext
{
const Methcla_Host* m_context;
public:
HostContext(const Methcla_Host* context)
: m_context(context)
{}
LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)
{
using namespace std::placeholders;
return LogStream(std::bind(m_context->log_line, m_context, _1, _2), logLevel);
}
};
class NoPorts
{
public:
enum Port { };
static size_t numPorts() { return 0; }
static Methcla_PortDescriptor descriptor(Port)
{
Methcla_PortDescriptor result;
std::memset(&result, 0, sizeof(result));
return result;
}
};
class PortDescriptor
{
public:
static Methcla_PortDescriptor make(Methcla_PortDirection direction, Methcla_PortType type, Methcla_PortFlags flags=kMethcla_PortFlags)
{
Methcla_PortDescriptor pd;
pd.direction = direction;
pd.type = type;
pd.flags = flags;
return pd;
}
static Methcla_PortDescriptor audioInput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Input, kMethcla_AudioPort, flags);
}
static Methcla_PortDescriptor audioOutput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Output, kMethcla_AudioPort, flags);
}
static Methcla_PortDescriptor controlInput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Input, kMethcla_ControlPort, flags);
}
static Methcla_PortDescriptor controlOutput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Output, kMethcla_ControlPort, flags);
}
};
template <class Options, class PortDescriptor> class StaticSynthOptions
{
public:
typedef Options Type;
static void
configure( const void* tag_buffer
, size_t tag_buffer_size
, const void* arg_buffer
, size_t arg_buffer_size
, Methcla_SynthOptions* options )
{
OSCPP::Server::ArgStream args(
OSCPP::ReadStream(tag_buffer, tag_buffer_size),
OSCPP::ReadStream(arg_buffer, arg_buffer_size)
);
new (options) Type(args);
}
static bool
port_descriptor( const Methcla_SynthOptions*
, Methcla_PortCount index
, Methcla_PortDescriptor* port )
{
if (index < PortDescriptor::numPorts())
{
*port = PortDescriptor::descriptor(static_cast<typename PortDescriptor::Port>(index));
return true;
}
return false;
}
};
template <class Synth, class Options, class PortDescriptor> class SynthClass
{
static void
construct( const Methcla_World* world
, const Methcla_SynthDef* synthDef
, const Methcla_SynthOptions* options
, Methcla_Synth* synth )
{
assert(world != nullptr);
assert(options != nullptr);
new (synth) Synth(World<Synth>(world), synthDef, *static_cast<const typename Options::Type*>(options));
}
static void
connect( Methcla_Synth* synth
, Methcla_PortCount port
, void* data)
{
static_cast<Synth*>(synth)->connect(static_cast<typename PortDescriptor::Port>(port), data);
}
static void
activate(const Methcla_World* world, Methcla_Synth* synth)
{
static_cast<Synth*>(synth)->activate(World<Synth>(world));
}
static void
process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames)
{
static_cast<Synth*>(synth)->process(World<Synth>(world), numFrames);
}
static void
destroy(const Methcla_World*, Methcla_Synth* synth)
{
static_cast<Synth*>(synth)->~Synth();
}
public:
void operator()(const Methcla_Host* host, const char* uri)
{
static const Methcla_SynthDef kClass =
{
uri,
sizeof(Synth),
sizeof(typename Options::Type),
Options::configure,
Options::port_descriptor,
construct,
connect,
activate,
process,
destroy
};
methcla_host_register_synthdef(host, &kClass);
}
};
template <class Synth, class Options, class Ports> using StaticSynthClass
= SynthClass<Synth, StaticSynthOptions<Options,Ports>, Ports>;
} }
#endif // METHCLA_PLUGIN_HPP_INCLUDED
<commit_msg>Rename m_world to m_context<commit_after>// Copyright 2013 Samplecount S.L.
//
// 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.
#ifndef METHCLA_PLUGIN_HPP_INCLUDED
#define METHCLA_PLUGIN_HPP_INCLUDED
#include <methcla/log.hpp>
#include <methcla/plugin.h>
#include <oscpp/server.hpp>
#include <functional>
#include <cstring>
// NOTE: This API is unstable and subject to change!
namespace Methcla { namespace Plugin {
template <class Synth> class World
{
const Methcla_World* m_context;
public:
World(const Methcla_World* context)
: m_context(context)
{ }
double sampleRate() const
{
return methcla_world_samplerate(m_context);
}
size_t blockSize() const
{
return methcla_world_block_size(m_context);
}
Methcla_Time currentTime() const
{
return methcla_world_current_time(m_context);
}
void* alloc(size_t size) const
{
return methcla_world_alloc(m_context, size);
}
void* allocAligned(size_t alignment, size_t size) const
{
return methcla_world_alloc_aligned(m_context, alignment, size);
}
void free(void* ptr)
{
methcla_world_free(m_context, ptr);
}
void performCommand(Methcla_HostPerformFunction perform, void* data)
{
methcla_world_perform_command(m_context, perform, data);
}
LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)
{
using namespace std::placeholders;
return LogStream(std::bind(m_context->log_line, m_context, _1, _2), logLevel);
}
void synthRetain(Synth* synth) const
{
methcla_world_synth_retain(m_context, synth);
}
void synthRelease(Synth* synth) const
{
methcla_world_synth_release(m_context, synth);
}
void synthDone(Synth* synth) const
{
methcla_world_synth_done(m_context, synth);
}
};
class HostContext
{
const Methcla_Host* m_context;
public:
HostContext(const Methcla_Host* context)
: m_context(context)
{}
LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)
{
using namespace std::placeholders;
return LogStream(std::bind(m_context->log_line, m_context, _1, _2), logLevel);
}
};
class NoPorts
{
public:
enum Port { };
static size_t numPorts() { return 0; }
static Methcla_PortDescriptor descriptor(Port)
{
Methcla_PortDescriptor result;
std::memset(&result, 0, sizeof(result));
return result;
}
};
class PortDescriptor
{
public:
static Methcla_PortDescriptor make(Methcla_PortDirection direction, Methcla_PortType type, Methcla_PortFlags flags=kMethcla_PortFlags)
{
Methcla_PortDescriptor pd;
pd.direction = direction;
pd.type = type;
pd.flags = flags;
return pd;
}
static Methcla_PortDescriptor audioInput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Input, kMethcla_AudioPort, flags);
}
static Methcla_PortDescriptor audioOutput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Output, kMethcla_AudioPort, flags);
}
static Methcla_PortDescriptor controlInput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Input, kMethcla_ControlPort, flags);
}
static Methcla_PortDescriptor controlOutput(Methcla_PortFlags flags=kMethcla_PortFlags)
{
return make(kMethcla_Output, kMethcla_ControlPort, flags);
}
};
template <class Options, class PortDescriptor> class StaticSynthOptions
{
public:
typedef Options Type;
static void
configure( const void* tag_buffer
, size_t tag_buffer_size
, const void* arg_buffer
, size_t arg_buffer_size
, Methcla_SynthOptions* options )
{
OSCPP::Server::ArgStream args(
OSCPP::ReadStream(tag_buffer, tag_buffer_size),
OSCPP::ReadStream(arg_buffer, arg_buffer_size)
);
new (options) Type(args);
}
static bool
port_descriptor( const Methcla_SynthOptions*
, Methcla_PortCount index
, Methcla_PortDescriptor* port )
{
if (index < PortDescriptor::numPorts())
{
*port = PortDescriptor::descriptor(static_cast<typename PortDescriptor::Port>(index));
return true;
}
return false;
}
};
template <class Synth, class Options, class PortDescriptor> class SynthClass
{
static void
construct( const Methcla_World* world
, const Methcla_SynthDef* synthDef
, const Methcla_SynthOptions* options
, Methcla_Synth* synth )
{
assert(world != nullptr);
assert(options != nullptr);
new (synth) Synth(World<Synth>(world), synthDef, *static_cast<const typename Options::Type*>(options));
}
static void
connect( Methcla_Synth* synth
, Methcla_PortCount port
, void* data)
{
static_cast<Synth*>(synth)->connect(static_cast<typename PortDescriptor::Port>(port), data);
}
static void
activate(const Methcla_World* world, Methcla_Synth* synth)
{
static_cast<Synth*>(synth)->activate(World<Synth>(world));
}
static void
process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames)
{
static_cast<Synth*>(synth)->process(World<Synth>(world), numFrames);
}
static void
destroy(const Methcla_World*, Methcla_Synth* synth)
{
static_cast<Synth*>(synth)->~Synth();
}
public:
void operator()(const Methcla_Host* host, const char* uri)
{
static const Methcla_SynthDef kClass =
{
uri,
sizeof(Synth),
sizeof(typename Options::Type),
Options::configure,
Options::port_descriptor,
construct,
connect,
activate,
process,
destroy
};
methcla_host_register_synthdef(host, &kClass);
}
};
template <class Synth, class Options, class Ports> using StaticSynthClass
= SynthClass<Synth, StaticSynthOptions<Options,Ports>, Ports>;
} }
#endif // METHCLA_PLUGIN_HPP_INCLUDED
<|endoftext|>
|
<commit_before><commit_msg>`AnyValue`: use `std::boolapha` to convert `bool` value to a string.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Bugfix: if active `Scene` was deleted, set active `Scene` to `nullptr`.<commit_after><|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <com/sun/star/drawing/XDrawPage.hpp>
#include <vcl/font.hxx>
#if defined( UNX )
#include <prex.h>
#include "GL/glxew.h"
#include <postx.h>
#endif
#if defined( _WIN32 )
#include "prewin.h"
#include "windows.h"
#include "postwin.h"
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include <vcl/window.hxx>
#include <vcl/syschild.hxx>
#include <vcl/sysdata.hxx>
#include <vcl/bitmapex.hxx>
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#if defined( _WIN32 )
#include <GL/glu.h>
#include <GL/glext.h>
#include <GL/wglext.h>
#elif defined( MACOSX )
#include "premac.h"
#include <Cocoa/Cocoa.h>
#include "postmac.h"
#elif defined( UNX )
#include <GL/glu.h>
#include <GL/glext.h>
#define GLX_GLXEXT_PROTOTYPES 1
#include <GL/glx.h>
#include <GL/glxext.h>
#endif
// Include GLM
#include <list>
#include "glm/glm.hpp"
#include "glm/gtx/transform.hpp"
#include "glm/gtx/euler_angles.hpp"
#include "glm/gtx/quaternion.hpp"
#define OPENGL_SCALE_VALUE 20
#define DEBUG_POSITIONING 0
#define RENDER_TO_FILE 0
typedef struct PosVecf3
{
float x;
float y;
float z;
}PosVecf3;
typedef std::vector<GLfloat> Line2DPointList;
typedef struct Bubble2DPointList
{
float x;
float y;
float xScale;
float yScale;
}Bubble2DPointList;
typedef struct Bubble2DCircle
{
float *pointBuf;
int bufLen;
}Bubble2DCircle;
struct RectanglePointList
{
float points[12];
};
typedef struct TextInfo
{
GLuint texture;
float x;
float y;
float z;
double rotation;
float vertex[12];
}TextInfo;
typedef std::vector<GLfloat> Area2DPointList;
typedef std::vector<GLfloat> PieSegment2DPointList;
/// Holds the information of our new child window
struct GLWindow
{
#if defined( _WIN32 )
HWND hWnd;
HDC hDC;
HGLRC hRC;
#elif defined( MACOSX )
#elif defined( UNX )
Display* dpy;
int screen;
XLIB_Window win;
#if defined( GLX_VERSION_1_3 ) && defined( GLX_EXT_texture_from_pixmap )
GLXFBConfig fbc;
#endif
XVisualInfo* vi;
GLXContext ctx;
bool HasGLXExtension( const char* name ) { return gluCheckExtension( (const GLubyte*) name, (const GLubyte*) GLXExtensions ); }
const char* GLXExtensions;
#endif
unsigned int bpp;
unsigned int Width;
unsigned int Height;
const GLubyte* GLExtensions;
bool HasGLExtension( const char* name ) { return gluCheckExtension( (const GLubyte*) name, GLExtensions ); }
};
class OpenGLRender
{
public:
OpenGLRender(com::sun::star::uno::Reference<
com::sun::star::drawing::XShape > xTarget );
~OpenGLRender();
int InitOpenGL(GLWindow);
int MoveModelf(PosVecf3 trans, PosVecf3 angle, PosVecf3 scale);
void SetWidth(int width);
void SetHeight(int height);
void Release();
#if RENDER_TO_FILE
int CreateBMPHeader(sal_uInt8 *bmpHeader, int xsize, int ysize);
#endif
int RenderLine2FBO(int wholeFlag);
int SetLine2DShapePoint(float x, float y, int listLength);
void SetLine2DColor(sal_uInt8 r, sal_uInt8 g, sal_uInt8 b);
void SetLine2DWidth(int width);
BitmapEx GetAsBitmap();
#if defined( _WIN32 )
bool InitMultisample(PIXELFORMATDESCRIPTOR pfd);
#endif
bool GetMSAASupport();
int GetMSAAFormat();
void SetColor(sal_uInt32 color);
int Bubble2DShapePoint(float x, float y, float directionX, float directionY);
int RenderBubble2FBO(int wholeFlag);
void prepareToRender();
void renderToBitmap();
void SetTransparency(sal_uInt32 transparency);
int RenderRectangleShape(bool bBorder, bool bFill);
int RectangleShapePoint(float x, float y, float directionX, float directionY);
int CreateTextTexture(const BitmapEx& rBitmapEx,
com::sun::star::awt::Point aPos, com::sun::star::awt::Size aSize, long rotation,
const com::sun::star::drawing::HomogenMatrix3& rTrans);
int RenderTextShape();
int SetArea2DShapePoint(float x, float y, int listLength);
int RenderArea2DShape();
void SetChartTransparencyGradient(long transparencyGradient);
void GeneratePieSegment2D(double, double, double, double);
int RenderPieSegment2DShape(float, float, float);
#if DEBUG_POSITIONING
void renderDebug();
#endif
void SetBackGroundColor(sal_uInt32 color1, sal_uInt32 color2);
private:
GLint LoadShaders(const char *vertexShader,const char *fragmentShader);
int CreateTextureObj(int width, int height);
int CreateRenderObj(int width, int height);
int CreateFrameBufferObj();
int RenderTexture(GLuint TexID);
int RenderTexture2FBO(GLuint TexID);
#if defined( _WIN32 )
int InitTempWindow(HWND *hwnd, int width, int height, PIXELFORMATDESCRIPTOR inPfd);
bool WGLisExtensionSupported(const char *extension);
#endif
int CreateMultiSampleFrameBufObj();
int Create2DCircle(int detail);
private:
// Projection matrix : default 45 degree Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
glm::mat4 m_Projection;
// Camera matrix
glm::mat4 m_View;
// Model matrix : an identity matrix (model will be at the origin)
glm::mat4 m_Model;
// Our ModelViewProjection : multiplication of our 3 matrices
glm::mat4 m_MVP;
GLint m_RenderProID;
GLuint m_VertexBuffer;
GLuint m_ColorBuffer;
GLint m_MatrixID;
GLint m_VertexID;
GLint m_ColorID;
GLint m_RenderVertexID;
GLint m_RenderTexCoordID;
GLint m_Line2DVertexID;
GLint m_Line2DWholeVertexID;
GLint m_Line2DColorID;
GLint m_RenderTexID;
GLuint m_RenderVertexBuf;
GLuint m_RenderTexCoordBuf;
GLuint m_TextureObj;
GLuint m_FboID;
GLuint m_RboID;
int m_iWidth;
int m_iHeight;
GLWindow glWin;
Line2DPointList m_Line2DPointList;
float m_fLineWidth;
std::list <Line2DPointList> m_Line2DShapePointList;
com::sun::star::uno::Reference< com::sun::star::drawing::XShape > mxRenderTarget;
bool mbArbMultisampleSupported;
int m_iArbMultisampleFormat;
GLint m_iSampleBufs;
GLint m_iSamples;
glm::vec4 m_2DColor;
GLuint m_frameBufferMS;
GLuint m_renderBufferColorMS;
GLuint m_renderBufferDepthMS;
Bubble2DCircle m_Bubble2DCircle;
std::list <Bubble2DPointList> m_Bubble2DShapePointList;
GLint m_CommonProID;
GLint m_2DVertexID;
GLint m_2DColorID;
float m_fZStep;
float m_fAlpha;
std::list <RectanglePointList> m_RectangleShapePointList;
// add for text
std::list <TextInfo> m_TextInfoList;
GLint m_TextProID;
GLint m_TextMatrixID;
GLint m_TextVertexID;
GLint m_TextTexCoordID;
GLuint m_TextTexCoordBuf;
GLint m_TextTexID;
Area2DPointList m_Area2DPointList;
std::list <Area2DPointList> m_Area2DShapePointList;
GLint m_BackgroundProID;
GLint m_BackgroundMatrixID;
GLint m_BackgroundVertexID;
GLint m_BackgroundColorID;
float m_BackgroundColor[16];
glm::vec4 m_ClearColor;
PieSegment2DPointList m_PieSegment2DPointList;
std::list <PieSegment2DPointList> m_PieSegment2DShapePointList;
#if DEBUG_POSITIONING
GLuint m_DebugProID;
GLuint m_DebugVertexID;
GLuint m_DebugColorID;
#endif
};
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>remove unused variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <com/sun/star/drawing/XDrawPage.hpp>
#include <vcl/font.hxx>
#if defined( UNX )
#include <prex.h>
#include "GL/glxew.h"
#include <postx.h>
#endif
#if defined( _WIN32 )
#include "prewin.h"
#include "windows.h"
#include "postwin.h"
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include <vcl/window.hxx>
#include <vcl/syschild.hxx>
#include <vcl/sysdata.hxx>
#include <vcl/bitmapex.hxx>
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#if defined( _WIN32 )
#include <GL/glu.h>
#include <GL/glext.h>
#include <GL/wglext.h>
#elif defined( MACOSX )
#include "premac.h"
#include <Cocoa/Cocoa.h>
#include "postmac.h"
#elif defined( UNX )
#include <GL/glu.h>
#include <GL/glext.h>
#define GLX_GLXEXT_PROTOTYPES 1
#include <GL/glx.h>
#include <GL/glxext.h>
#endif
// Include GLM
#include <list>
#include "glm/glm.hpp"
#include "glm/gtx/transform.hpp"
#include "glm/gtx/euler_angles.hpp"
#include "glm/gtx/quaternion.hpp"
#define OPENGL_SCALE_VALUE 20
#define DEBUG_POSITIONING 0
#define RENDER_TO_FILE 0
typedef struct PosVecf3
{
float x;
float y;
float z;
}PosVecf3;
typedef std::vector<GLfloat> Line2DPointList;
typedef struct Bubble2DPointList
{
float x;
float y;
float xScale;
float yScale;
}Bubble2DPointList;
typedef struct Bubble2DCircle
{
float *pointBuf;
int bufLen;
}Bubble2DCircle;
struct RectanglePointList
{
float points[12];
};
typedef struct TextInfo
{
GLuint texture;
float x;
float y;
float z;
double rotation;
float vertex[12];
}TextInfo;
typedef std::vector<GLfloat> Area2DPointList;
typedef std::vector<GLfloat> PieSegment2DPointList;
/// Holds the information of our new child window
struct GLWindow
{
#if defined( _WIN32 )
HWND hWnd;
HDC hDC;
HGLRC hRC;
#elif defined( MACOSX )
#elif defined( UNX )
Display* dpy;
int screen;
XLIB_Window win;
#if defined( GLX_VERSION_1_3 ) && defined( GLX_EXT_texture_from_pixmap )
GLXFBConfig fbc;
#endif
XVisualInfo* vi;
GLXContext ctx;
bool HasGLXExtension( const char* name ) { return gluCheckExtension( (const GLubyte*) name, (const GLubyte*) GLXExtensions ); }
const char* GLXExtensions;
#endif
unsigned int bpp;
unsigned int Width;
unsigned int Height;
const GLubyte* GLExtensions;
bool HasGLExtension( const char* name ) { return gluCheckExtension( (const GLubyte*) name, GLExtensions ); }
};
class OpenGLRender
{
public:
OpenGLRender(com::sun::star::uno::Reference<
com::sun::star::drawing::XShape > xTarget );
~OpenGLRender();
int InitOpenGL(GLWindow);
int MoveModelf(PosVecf3 trans, PosVecf3 angle, PosVecf3 scale);
void SetWidth(int width);
void SetHeight(int height);
void Release();
#if RENDER_TO_FILE
int CreateBMPHeader(sal_uInt8 *bmpHeader, int xsize, int ysize);
#endif
int RenderLine2FBO(int wholeFlag);
int SetLine2DShapePoint(float x, float y, int listLength);
void SetLine2DColor(sal_uInt8 r, sal_uInt8 g, sal_uInt8 b);
void SetLine2DWidth(int width);
BitmapEx GetAsBitmap();
#if defined( _WIN32 )
bool InitMultisample(PIXELFORMATDESCRIPTOR pfd);
#endif
bool GetMSAASupport();
int GetMSAAFormat();
void SetColor(sal_uInt32 color);
int Bubble2DShapePoint(float x, float y, float directionX, float directionY);
int RenderBubble2FBO(int wholeFlag);
void prepareToRender();
void renderToBitmap();
void SetTransparency(sal_uInt32 transparency);
int RenderRectangleShape(bool bBorder, bool bFill);
int RectangleShapePoint(float x, float y, float directionX, float directionY);
int CreateTextTexture(const BitmapEx& rBitmapEx,
com::sun::star::awt::Point aPos, com::sun::star::awt::Size aSize, long rotation,
const com::sun::star::drawing::HomogenMatrix3& rTrans);
int RenderTextShape();
int SetArea2DShapePoint(float x, float y, int listLength);
int RenderArea2DShape();
void SetChartTransparencyGradient(long transparencyGradient);
void GeneratePieSegment2D(double, double, double, double);
int RenderPieSegment2DShape(float, float, float);
#if DEBUG_POSITIONING
void renderDebug();
#endif
void SetBackGroundColor(sal_uInt32 color1, sal_uInt32 color2);
private:
GLint LoadShaders(const char *vertexShader,const char *fragmentShader);
int CreateTextureObj(int width, int height);
int CreateRenderObj(int width, int height);
int CreateFrameBufferObj();
int RenderTexture(GLuint TexID);
int RenderTexture2FBO(GLuint TexID);
#if defined( _WIN32 )
int InitTempWindow(HWND *hwnd, int width, int height, PIXELFORMATDESCRIPTOR inPfd);
bool WGLisExtensionSupported(const char *extension);
#endif
int CreateMultiSampleFrameBufObj();
int Create2DCircle(int detail);
private:
// Projection matrix : default 45 degree Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
glm::mat4 m_Projection;
// Camera matrix
glm::mat4 m_View;
// Model matrix : an identity matrix (model will be at the origin)
glm::mat4 m_Model;
// Our ModelViewProjection : multiplication of our 3 matrices
glm::mat4 m_MVP;
GLint m_RenderProID;
GLuint m_VertexBuffer;
GLuint m_ColorBuffer;
GLint m_MatrixID;
GLint m_VertexID;
GLint m_ColorID;
GLint m_RenderVertexID;
GLint m_RenderTexCoordID;
GLint m_Line2DVertexID;
GLint m_Line2DWholeVertexID;
GLint m_Line2DColorID;
GLint m_RenderTexID;
GLuint m_RenderVertexBuf;
GLuint m_RenderTexCoordBuf;
GLuint m_TextureObj;
GLuint m_FboID;
GLuint m_RboID;
int m_iWidth;
int m_iHeight;
GLWindow glWin;
Line2DPointList m_Line2DPointList;
float m_fLineWidth;
std::list <Line2DPointList> m_Line2DShapePointList;
com::sun::star::uno::Reference< com::sun::star::drawing::XShape > mxRenderTarget;
bool mbArbMultisampleSupported;
int m_iArbMultisampleFormat;
GLint m_iSampleBufs;
GLint m_iSamples;
glm::vec4 m_2DColor;
GLuint m_frameBufferMS;
GLuint m_renderBufferColorMS;
GLuint m_renderBufferDepthMS;
Bubble2DCircle m_Bubble2DCircle;
std::list <Bubble2DPointList> m_Bubble2DShapePointList;
GLint m_CommonProID;
GLint m_2DVertexID;
GLint m_2DColorID;
float m_fZStep;
float m_fAlpha;
std::list <RectanglePointList> m_RectangleShapePointList;
// add for text
std::list <TextInfo> m_TextInfoList;
GLint m_TextProID;
GLint m_TextMatrixID;
GLint m_TextVertexID;
GLint m_TextTexCoordID;
GLuint m_TextTexCoordBuf;
GLint m_TextTexID;
Area2DPointList m_Area2DPointList;
std::list <Area2DPointList> m_Area2DShapePointList;
GLint m_BackgroundProID;
GLint m_BackgroundMatrixID;
GLint m_BackgroundVertexID;
GLint m_BackgroundColorID;
float m_BackgroundColor[16];
glm::vec4 m_ClearColor;
std::list <PieSegment2DPointList> m_PieSegment2DShapePointList;
#if DEBUG_POSITIONING
GLuint m_DebugProID;
GLuint m_DebugVertexID;
GLuint m_DebugColorID;
#endif
};
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "command_manager.hh"
#include "utils.hh"
#include "assert.hh"
#include "context.hh"
#include "shell_manager.hh"
#include <algorithm>
namespace Kakoune
{
bool CommandManager::command_defined(const String& command_name) const
{
return m_commands.find(command_name) != m_commands.end();
}
void CommandManager::register_command(const String& command_name,
Command command,
unsigned flags,
const CommandCompleter& completer)
{
m_commands[command_name] = CommandDescriptor { command, flags, completer };
}
void CommandManager::register_commands(const memoryview<String>& command_names,
Command command,
unsigned flags,
const CommandCompleter& completer)
{
for (auto command_name : command_names)
register_command(command_name, command, flags, completer);
}
static bool is_blank(char c)
{
return c == ' ' or c == '\t' or c == '\n';
}
typedef std::vector<std::pair<size_t, size_t>> TokenList;
static TokenList split(const String& line)
{
TokenList result;
size_t pos = 0;
while (pos < line.length())
{
while(is_blank(line[pos]) and pos != line.length())
++pos;
size_t token_start = pos;
if (line[pos] == '"' or line[pos] == '\'' or line[pos] == '`')
{
char delimiter = line[pos];
++pos;
token_start = delimiter == '`' ? pos - 1 : pos;
while ((line[pos] != delimiter or line[pos-1] == '\\') and
pos != line.length())
++pos;
if (delimiter == '`' and line[pos] == '`')
++pos;
}
else
while (not is_blank(line[pos]) and pos != line.length() and
(line[pos] != ';' or line[pos-1] == '\\'))
++pos;
if (token_start != pos)
result.push_back(std::make_pair(token_start, pos));
if (line[pos] == ';')
result.push_back(std::make_pair(pos, pos+1));
++pos;
}
return result;
}
struct command_not_found : runtime_error
{
command_not_found(const String& command)
: runtime_error(command + " : no such command") {}
};
void CommandManager::execute(const String& command_line,
const Context& context,
const EnvVarMap& env_vars)
{
TokenList tokens = split(command_line);
if (tokens.empty())
return;
std::vector<String> params;
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
params.push_back(command_line.substr(it->first,
it->second - it->first));
}
execute(params, context, env_vars);
}
static void shell_eval(std::vector<String>& params,
const String& cmdline,
const Context& context,
const EnvVarMap& env_vars)
{
String output = ShellManager::instance().eval(cmdline, context, env_vars);
TokenList tokens = split(output);
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
params.push_back(output.substr(it->first,
it->second - it->first));
}
}
void CommandManager::execute(const CommandParameters& params,
const Context& context,
const EnvVarMap& env_vars)
{
if (params.empty())
return;
auto begin = params.begin();
auto end = begin;
while (true)
{
while (end != params.end() and *end != ";")
++end;
if (end != begin)
{
std::vector<String> expanded_params;
auto command_it = m_commands.find(*begin);
if (command_it == m_commands.end() and
begin->front() == '`' and begin->back() == '`')
{
shell_eval(expanded_params,
begin->substr(1, begin->length() - 2),
context, env_vars);
if (not expanded_params.empty())
{
command_it = m_commands.find(expanded_params[0]);
expanded_params.erase(expanded_params.begin());
}
}
if (command_it == m_commands.end())
throw command_not_found(*begin);
if (command_it->second.flags & IgnoreSemiColons)
end = params.end();
if (command_it->second.flags & DeferredShellEval)
command_it->second.command(CommandParameters(begin + 1, end), context);
else
{
for (auto param = begin+1; param != end; ++param)
{
if (param->front() == '`' and param->back() == '`')
shell_eval(expanded_params,
param->substr(1, param->length() - 2),
context, env_vars);
else
expanded_params.push_back(*param);
}
command_it->second.command(expanded_params, context);
}
}
if (end == params.end())
break;
begin = end+1;
end = begin;
}
}
Completions CommandManager::complete(const String& command_line, size_t cursor_pos)
{
TokenList tokens = split(command_line);
size_t token_to_complete = tokens.size();
for (size_t i = 0; i < tokens.size(); ++i)
{
if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos)
{
token_to_complete = i;
break;
}
}
if (token_to_complete == 0 or tokens.empty()) // command name completion
{
size_t cmd_start = tokens.empty() ? 0 : tokens[0].first;
Completions result(cmd_start, cursor_pos);
String prefix = command_line.substr(cmd_start,
cursor_pos - cmd_start);
for (auto& command : m_commands)
{
if (command.first.substr(0, prefix.length()) == prefix)
result.candidates.push_back(command.first);
}
return result;
}
assert(not tokens.empty());
String command_name =
command_line.substr(tokens[0].first,
tokens[0].second - tokens[0].first);
auto command_it = m_commands.find(command_name);
if (command_it == m_commands.end() or not command_it->second.completer)
return Completions();
std::vector<String> params;
for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)
{
params.push_back(command_line.substr(it->first,
it->second - it->first));
}
size_t start = token_to_complete < tokens.size() ?
tokens[token_to_complete].first : cursor_pos;
Completions result(start , cursor_pos);
size_t cursor_pos_in_token = cursor_pos - start;
result.candidates = command_it->second.completer(params,
token_to_complete - 1,
cursor_pos_in_token);
return result;
}
CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params,
size_t token_to_complete,
size_t pos_in_token) const
{
if (token_to_complete >= m_completers.size())
return CandidateList();
// it is possible to try to complete a new argument
assert(token_to_complete <= params.size());
const String& argument = token_to_complete < params.size() ?
params[token_to_complete] : String();
return m_completers[token_to_complete](argument, pos_in_token);
}
}
<commit_msg>sort command names completion candidates<commit_after>#include "command_manager.hh"
#include "utils.hh"
#include "assert.hh"
#include "context.hh"
#include "shell_manager.hh"
#include <algorithm>
namespace Kakoune
{
bool CommandManager::command_defined(const String& command_name) const
{
return m_commands.find(command_name) != m_commands.end();
}
void CommandManager::register_command(const String& command_name,
Command command,
unsigned flags,
const CommandCompleter& completer)
{
m_commands[command_name] = CommandDescriptor { command, flags, completer };
}
void CommandManager::register_commands(const memoryview<String>& command_names,
Command command,
unsigned flags,
const CommandCompleter& completer)
{
for (auto command_name : command_names)
register_command(command_name, command, flags, completer);
}
static bool is_blank(char c)
{
return c == ' ' or c == '\t' or c == '\n';
}
typedef std::vector<std::pair<size_t, size_t>> TokenList;
static TokenList split(const String& line)
{
TokenList result;
size_t pos = 0;
while (pos < line.length())
{
while(is_blank(line[pos]) and pos != line.length())
++pos;
size_t token_start = pos;
if (line[pos] == '"' or line[pos] == '\'' or line[pos] == '`')
{
char delimiter = line[pos];
++pos;
token_start = delimiter == '`' ? pos - 1 : pos;
while ((line[pos] != delimiter or line[pos-1] == '\\') and
pos != line.length())
++pos;
if (delimiter == '`' and line[pos] == '`')
++pos;
}
else
while (not is_blank(line[pos]) and pos != line.length() and
(line[pos] != ';' or line[pos-1] == '\\'))
++pos;
if (token_start != pos)
result.push_back(std::make_pair(token_start, pos));
if (line[pos] == ';')
result.push_back(std::make_pair(pos, pos+1));
++pos;
}
return result;
}
struct command_not_found : runtime_error
{
command_not_found(const String& command)
: runtime_error(command + " : no such command") {}
};
void CommandManager::execute(const String& command_line,
const Context& context,
const EnvVarMap& env_vars)
{
TokenList tokens = split(command_line);
if (tokens.empty())
return;
std::vector<String> params;
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
params.push_back(command_line.substr(it->first,
it->second - it->first));
}
execute(params, context, env_vars);
}
static void shell_eval(std::vector<String>& params,
const String& cmdline,
const Context& context,
const EnvVarMap& env_vars)
{
String output = ShellManager::instance().eval(cmdline, context, env_vars);
TokenList tokens = split(output);
for (auto it = tokens.begin(); it != tokens.end(); ++it)
{
params.push_back(output.substr(it->first,
it->second - it->first));
}
}
void CommandManager::execute(const CommandParameters& params,
const Context& context,
const EnvVarMap& env_vars)
{
if (params.empty())
return;
auto begin = params.begin();
auto end = begin;
while (true)
{
while (end != params.end() and *end != ";")
++end;
if (end != begin)
{
std::vector<String> expanded_params;
auto command_it = m_commands.find(*begin);
if (command_it == m_commands.end() and
begin->front() == '`' and begin->back() == '`')
{
shell_eval(expanded_params,
begin->substr(1, begin->length() - 2),
context, env_vars);
if (not expanded_params.empty())
{
command_it = m_commands.find(expanded_params[0]);
expanded_params.erase(expanded_params.begin());
}
}
if (command_it == m_commands.end())
throw command_not_found(*begin);
if (command_it->second.flags & IgnoreSemiColons)
end = params.end();
if (command_it->second.flags & DeferredShellEval)
command_it->second.command(CommandParameters(begin + 1, end), context);
else
{
for (auto param = begin+1; param != end; ++param)
{
if (param->front() == '`' and param->back() == '`')
shell_eval(expanded_params,
param->substr(1, param->length() - 2),
context, env_vars);
else
expanded_params.push_back(*param);
}
command_it->second.command(expanded_params, context);
}
}
if (end == params.end())
break;
begin = end+1;
end = begin;
}
}
Completions CommandManager::complete(const String& command_line, size_t cursor_pos)
{
TokenList tokens = split(command_line);
size_t token_to_complete = tokens.size();
for (size_t i = 0; i < tokens.size(); ++i)
{
if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos)
{
token_to_complete = i;
break;
}
}
if (token_to_complete == 0 or tokens.empty()) // command name completion
{
size_t cmd_start = tokens.empty() ? 0 : tokens[0].first;
Completions result(cmd_start, cursor_pos);
String prefix = command_line.substr(cmd_start,
cursor_pos - cmd_start);
for (auto& command : m_commands)
{
if (command.first.substr(0, prefix.length()) == prefix)
result.candidates.push_back(command.first);
}
std::sort(result.candidates.begin(), result.candidates.end());
return result;
}
assert(not tokens.empty());
String command_name =
command_line.substr(tokens[0].first,
tokens[0].second - tokens[0].first);
auto command_it = m_commands.find(command_name);
if (command_it == m_commands.end() or not command_it->second.completer)
return Completions();
std::vector<String> params;
for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)
{
params.push_back(command_line.substr(it->first,
it->second - it->first));
}
size_t start = token_to_complete < tokens.size() ?
tokens[token_to_complete].first : cursor_pos;
Completions result(start , cursor_pos);
size_t cursor_pos_in_token = cursor_pos - start;
result.candidates = command_it->second.completer(params,
token_to_complete - 1,
cursor_pos_in_token);
return result;
}
CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params,
size_t token_to_complete,
size_t pos_in_token) const
{
if (token_to_complete >= m_completers.size())
return CandidateList();
// it is possible to try to complete a new argument
assert(token_to_complete <= params.size());
const String& argument = token_to_complete < params.size() ?
params[token_to_complete] : String();
return m_completers[token_to_complete](argument, pos_in_token);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 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/views/cookie_info_view.h"
#include <algorithm>
#include "app/l10n_util.h"
#include "base/i18n/time_formatting.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/cookies_tree_model.h"
#include "chrome/browser/profile.h"
#include "gfx/canvas.h"
#include "gfx/color_utils.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/border.h"
#include "views/grid_layout.h"
#include "views/controls/label.h"
#include "views/controls/button/native_button.h"
#include "views/controls/tree/tree_view.h"
#include "views/controls/textfield/textfield.h"
#include "views/standard_layout.h"
static const int kCookieInfoViewBorderSize = 1;
static const int kCookieInfoViewInsetSize = 3;
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, public:
CookieInfoView::CookieInfoView(bool editable_expiration_date)
: name_label_(NULL),
name_value_field_(NULL),
content_label_(NULL),
content_value_field_(NULL),
domain_label_(NULL),
domain_value_field_(NULL),
path_label_(NULL),
path_value_field_(NULL),
send_for_label_(NULL),
send_for_value_field_(NULL),
created_label_(NULL),
created_value_field_(NULL),
expires_label_(NULL),
expires_value_field_(NULL),
expires_value_combobox_(NULL),
expire_view_(NULL),
editable_expiration_date_(editable_expiration_date),
delegate_(NULL) {
}
CookieInfoView::~CookieInfoView() {
}
void CookieInfoView::SetCookie(
const std::string& domain,
const net::CookieMonster::CanonicalCookie& cookie) {
name_value_field_->SetText(UTF8ToWide(cookie.Name()));
content_value_field_->SetText(UTF8ToWide(cookie.Value()));
domain_value_field_->SetText(UTF8ToWide(domain));
path_value_field_->SetText(UTF8ToWide(cookie.Path()));
created_value_field_->SetText(
base::TimeFormatFriendlyDateAndTime(cookie.CreationDate()));
std::wstring expire_text = cookie.DoesExpire() ?
base::TimeFormatFriendlyDateAndTime(cookie.ExpiryDate()) :
l10n_util::GetString(IDS_COOKIES_COOKIE_EXPIRES_SESSION);
if (editable_expiration_date_) {
expire_combo_values_.clear();
if (cookie.DoesExpire())
expire_combo_values_.push_back(expire_text);
expire_combo_values_.push_back(
l10n_util::GetString(IDS_COOKIES_COOKIE_EXPIRES_SESSION));
expires_value_combobox_->ModelChanged();
expires_value_combobox_->SetSelectedItem(0);
expires_value_combobox_->SetEnabled(true);
} else {
expires_value_field_->SetText(expire_text);
}
send_for_value_field_->SetText(cookie.IsSecure() ?
l10n_util::GetString(IDS_COOKIES_COOKIE_SENDFOR_SECURE) :
l10n_util::GetString(IDS_COOKIES_COOKIE_SENDFOR_ANY));
EnableCookieDisplay(true);
Layout();
}
void CookieInfoView::SetCookieString(const GURL& url,
const std::string& cookie_line) {
net::CookieMonster::ParsedCookie pc(cookie_line);
net::CookieMonster::CanonicalCookie cookie(url, pc);
SetCookie(pc.HasDomain() ? pc.Domain() : url.host(), cookie);
}
void CookieInfoView::ClearCookieDisplay() {
std::wstring no_cookie_string =
l10n_util::GetString(IDS_COOKIES_COOKIE_NONESELECTED);
name_value_field_->SetText(no_cookie_string);
content_value_field_->SetText(no_cookie_string);
domain_value_field_->SetText(no_cookie_string);
path_value_field_->SetText(no_cookie_string);
send_for_value_field_->SetText(no_cookie_string);
created_value_field_->SetText(no_cookie_string);
if (expires_value_field_)
expires_value_field_->SetText(no_cookie_string);
EnableCookieDisplay(false);
}
void CookieInfoView::EnableCookieDisplay(bool enabled) {
name_value_field_->SetEnabled(enabled);
content_value_field_->SetEnabled(enabled);
domain_value_field_->SetEnabled(enabled);
path_value_field_->SetEnabled(enabled);
send_for_value_field_->SetEnabled(enabled);
created_value_field_->SetEnabled(enabled);
if (expires_value_field_)
expires_value_field_->SetEnabled(enabled);
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, views::View overrides.
void CookieInfoView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && child == this)
Init();
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, views::Combobox::Listener overrides.
void CookieInfoView::ItemChanged(views::Combobox* combo_box,
int prev_index,
int new_index) {
DCHECK(combo_box == expires_value_combobox_);
if (delegate_)
delegate_->ModifyExpireDate(new_index != 0);
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, ComboboxModel overrides.
int CookieInfoView::GetItemCount() {
return static_cast<int>(expire_combo_values_.size());
}
std::wstring CookieInfoView::GetItemAt(int index) {
return expire_combo_values_[index];
}
void CookieInfoView::AddLabelRow(int layout_id, views::GridLayout* layout,
views::View* label, views::View* value) {
layout->StartRow(0, layout_id);
layout->AddView(label);
layout->AddView(value, 2, 1, views::GridLayout::FILL,
views::GridLayout::CENTER);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
}
void CookieInfoView::AddControlRow(int layout_id, views::GridLayout* layout,
views::View* label, views::View* control) {
layout->StartRow(0, layout_id);
layout->AddView(label);
layout->AddView(control, 1, 1);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, private:
void CookieInfoView::Init() {
// Ensure we don't run this more than once and leak memory.
DCHECK(!name_label_);
SkColor border_color = color_utils::GetSysSkColor(COLOR_3DSHADOW);
views::Border* border = views::Border::CreateSolidBorder(
kCookieInfoViewBorderSize, border_color);
set_border(border);
name_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_NAME_LABEL));
name_value_field_ = new views::Textfield;
content_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_CONTENT_LABEL));
content_value_field_ = new views::Textfield;
domain_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_DOMAIN_LABEL));
domain_value_field_ = new views::Textfield;
path_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_PATH_LABEL));
path_value_field_ = new views::Textfield;
send_for_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_SENDFOR_LABEL));
send_for_value_field_ = new views::Textfield;
created_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_CREATED_LABEL));
created_value_field_ = new views::Textfield;
expires_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_EXPIRES_LABEL));
if (editable_expiration_date_)
expires_value_combobox_ = new views::Combobox(this);
else
expires_value_field_ = new views::Textfield;
using views::GridLayout;
using views::ColumnSet;
GridLayout* layout = new GridLayout(this);
layout->SetInsets(kCookieInfoViewInsetSize,
kCookieInfoViewInsetSize,
kCookieInfoViewInsetSize,
kCookieInfoViewInsetSize);
SetLayoutManager(layout);
int three_column_layout_id = 0;
ColumnSet* column_set = layout->AddColumnSet(three_column_layout_id);
column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1,
GridLayout::USE_PREF, 0, 0);
AddLabelRow(three_column_layout_id, layout, name_label_, name_value_field_);
AddLabelRow(three_column_layout_id, layout, content_label_,
content_value_field_);
AddLabelRow(three_column_layout_id, layout, domain_label_,
domain_value_field_);
AddLabelRow(three_column_layout_id, layout, path_label_, path_value_field_);
AddLabelRow(three_column_layout_id, layout, send_for_label_,
send_for_value_field_);
AddLabelRow(three_column_layout_id, layout, created_label_,
created_value_field_);
if (editable_expiration_date_) {
AddControlRow(three_column_layout_id, layout, expires_label_,
expires_value_combobox_);
} else {
AddLabelRow(three_column_layout_id, layout, expires_label_,
expires_value_field_);
}
// Color these borderless text areas the same as the containing dialog.
SkColor text_area_background = color_utils::GetSysSkColor(COLOR_3DFACE);
// Now that the Textfields are in the view hierarchy, we can initialize them.
name_value_field_->SetReadOnly(true);
name_value_field_->RemoveBorder();
name_value_field_->SetBackgroundColor(text_area_background);
content_value_field_->SetReadOnly(true);
content_value_field_->RemoveBorder();
content_value_field_->SetBackgroundColor(text_area_background);
domain_value_field_->SetReadOnly(true);
domain_value_field_->RemoveBorder();
domain_value_field_->SetBackgroundColor(text_area_background);
path_value_field_->SetReadOnly(true);
path_value_field_->RemoveBorder();
path_value_field_->SetBackgroundColor(text_area_background);
send_for_value_field_->SetReadOnly(true);
send_for_value_field_->RemoveBorder();
send_for_value_field_->SetBackgroundColor(text_area_background);
created_value_field_->SetReadOnly(true);
created_value_field_->RemoveBorder();
created_value_field_->SetBackgroundColor(text_area_background);
if (expires_value_field_) {
expires_value_field_->SetReadOnly(true);
expires_value_field_->RemoveBorder();
expires_value_field_->SetBackgroundColor(text_area_background);
}
}
<commit_msg>Register the cookie info view as listener to the expiry date combobox.<commit_after>// Copyright (c) 2010 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/views/cookie_info_view.h"
#include <algorithm>
#include "app/l10n_util.h"
#include "base/i18n/time_formatting.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/cookies_tree_model.h"
#include "chrome/browser/profile.h"
#include "gfx/canvas.h"
#include "gfx/color_utils.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/border.h"
#include "views/grid_layout.h"
#include "views/controls/label.h"
#include "views/controls/button/native_button.h"
#include "views/controls/tree/tree_view.h"
#include "views/controls/textfield/textfield.h"
#include "views/standard_layout.h"
static const int kCookieInfoViewBorderSize = 1;
static const int kCookieInfoViewInsetSize = 3;
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, public:
CookieInfoView::CookieInfoView(bool editable_expiration_date)
: name_label_(NULL),
name_value_field_(NULL),
content_label_(NULL),
content_value_field_(NULL),
domain_label_(NULL),
domain_value_field_(NULL),
path_label_(NULL),
path_value_field_(NULL),
send_for_label_(NULL),
send_for_value_field_(NULL),
created_label_(NULL),
created_value_field_(NULL),
expires_label_(NULL),
expires_value_field_(NULL),
expires_value_combobox_(NULL),
expire_view_(NULL),
editable_expiration_date_(editable_expiration_date),
delegate_(NULL) {
}
CookieInfoView::~CookieInfoView() {
}
void CookieInfoView::SetCookie(
const std::string& domain,
const net::CookieMonster::CanonicalCookie& cookie) {
name_value_field_->SetText(UTF8ToWide(cookie.Name()));
content_value_field_->SetText(UTF8ToWide(cookie.Value()));
domain_value_field_->SetText(UTF8ToWide(domain));
path_value_field_->SetText(UTF8ToWide(cookie.Path()));
created_value_field_->SetText(
base::TimeFormatFriendlyDateAndTime(cookie.CreationDate()));
std::wstring expire_text = cookie.DoesExpire() ?
base::TimeFormatFriendlyDateAndTime(cookie.ExpiryDate()) :
l10n_util::GetString(IDS_COOKIES_COOKIE_EXPIRES_SESSION);
if (editable_expiration_date_) {
expire_combo_values_.clear();
if (cookie.DoesExpire())
expire_combo_values_.push_back(expire_text);
expire_combo_values_.push_back(
l10n_util::GetString(IDS_COOKIES_COOKIE_EXPIRES_SESSION));
expires_value_combobox_->ModelChanged();
expires_value_combobox_->SetSelectedItem(0);
expires_value_combobox_->SetEnabled(true);
expires_value_combobox_->set_listener(this);
} else {
expires_value_field_->SetText(expire_text);
}
send_for_value_field_->SetText(cookie.IsSecure() ?
l10n_util::GetString(IDS_COOKIES_COOKIE_SENDFOR_SECURE) :
l10n_util::GetString(IDS_COOKIES_COOKIE_SENDFOR_ANY));
EnableCookieDisplay(true);
Layout();
}
void CookieInfoView::SetCookieString(const GURL& url,
const std::string& cookie_line) {
net::CookieMonster::ParsedCookie pc(cookie_line);
net::CookieMonster::CanonicalCookie cookie(url, pc);
SetCookie(pc.HasDomain() ? pc.Domain() : url.host(), cookie);
}
void CookieInfoView::ClearCookieDisplay() {
std::wstring no_cookie_string =
l10n_util::GetString(IDS_COOKIES_COOKIE_NONESELECTED);
name_value_field_->SetText(no_cookie_string);
content_value_field_->SetText(no_cookie_string);
domain_value_field_->SetText(no_cookie_string);
path_value_field_->SetText(no_cookie_string);
send_for_value_field_->SetText(no_cookie_string);
created_value_field_->SetText(no_cookie_string);
if (expires_value_field_)
expires_value_field_->SetText(no_cookie_string);
EnableCookieDisplay(false);
}
void CookieInfoView::EnableCookieDisplay(bool enabled) {
name_value_field_->SetEnabled(enabled);
content_value_field_->SetEnabled(enabled);
domain_value_field_->SetEnabled(enabled);
path_value_field_->SetEnabled(enabled);
send_for_value_field_->SetEnabled(enabled);
created_value_field_->SetEnabled(enabled);
if (expires_value_field_)
expires_value_field_->SetEnabled(enabled);
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, views::View overrides.
void CookieInfoView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && child == this)
Init();
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, views::Combobox::Listener overrides.
void CookieInfoView::ItemChanged(views::Combobox* combo_box,
int prev_index,
int new_index) {
DCHECK(combo_box == expires_value_combobox_);
if (delegate_)
delegate_->ModifyExpireDate(new_index != 0);
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, ComboboxModel overrides.
int CookieInfoView::GetItemCount() {
return static_cast<int>(expire_combo_values_.size());
}
std::wstring CookieInfoView::GetItemAt(int index) {
return expire_combo_values_[index];
}
void CookieInfoView::AddLabelRow(int layout_id, views::GridLayout* layout,
views::View* label, views::View* value) {
layout->StartRow(0, layout_id);
layout->AddView(label);
layout->AddView(value, 2, 1, views::GridLayout::FILL,
views::GridLayout::CENTER);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
}
void CookieInfoView::AddControlRow(int layout_id, views::GridLayout* layout,
views::View* label, views::View* control) {
layout->StartRow(0, layout_id);
layout->AddView(label);
layout->AddView(control, 1, 1);
layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);
}
///////////////////////////////////////////////////////////////////////////////
// CookieInfoView, private:
void CookieInfoView::Init() {
// Ensure we don't run this more than once and leak memory.
DCHECK(!name_label_);
SkColor border_color = color_utils::GetSysSkColor(COLOR_3DSHADOW);
views::Border* border = views::Border::CreateSolidBorder(
kCookieInfoViewBorderSize, border_color);
set_border(border);
name_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_NAME_LABEL));
name_value_field_ = new views::Textfield;
content_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_CONTENT_LABEL));
content_value_field_ = new views::Textfield;
domain_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_DOMAIN_LABEL));
domain_value_field_ = new views::Textfield;
path_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_PATH_LABEL));
path_value_field_ = new views::Textfield;
send_for_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_SENDFOR_LABEL));
send_for_value_field_ = new views::Textfield;
created_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_CREATED_LABEL));
created_value_field_ = new views::Textfield;
expires_label_ = new views::Label(
l10n_util::GetString(IDS_COOKIES_COOKIE_EXPIRES_LABEL));
if (editable_expiration_date_)
expires_value_combobox_ = new views::Combobox(this);
else
expires_value_field_ = new views::Textfield;
using views::GridLayout;
using views::ColumnSet;
GridLayout* layout = new GridLayout(this);
layout->SetInsets(kCookieInfoViewInsetSize,
kCookieInfoViewInsetSize,
kCookieInfoViewInsetSize,
kCookieInfoViewInsetSize);
SetLayoutManager(layout);
int three_column_layout_id = 0;
ColumnSet* column_set = layout->AddColumnSet(three_column_layout_id);
column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1,
GridLayout::USE_PREF, 0, 0);
AddLabelRow(three_column_layout_id, layout, name_label_, name_value_field_);
AddLabelRow(three_column_layout_id, layout, content_label_,
content_value_field_);
AddLabelRow(three_column_layout_id, layout, domain_label_,
domain_value_field_);
AddLabelRow(three_column_layout_id, layout, path_label_, path_value_field_);
AddLabelRow(three_column_layout_id, layout, send_for_label_,
send_for_value_field_);
AddLabelRow(three_column_layout_id, layout, created_label_,
created_value_field_);
if (editable_expiration_date_) {
AddControlRow(three_column_layout_id, layout, expires_label_,
expires_value_combobox_);
} else {
AddLabelRow(three_column_layout_id, layout, expires_label_,
expires_value_field_);
}
// Color these borderless text areas the same as the containing dialog.
SkColor text_area_background = color_utils::GetSysSkColor(COLOR_3DFACE);
// Now that the Textfields are in the view hierarchy, we can initialize them.
name_value_field_->SetReadOnly(true);
name_value_field_->RemoveBorder();
name_value_field_->SetBackgroundColor(text_area_background);
content_value_field_->SetReadOnly(true);
content_value_field_->RemoveBorder();
content_value_field_->SetBackgroundColor(text_area_background);
domain_value_field_->SetReadOnly(true);
domain_value_field_->RemoveBorder();
domain_value_field_->SetBackgroundColor(text_area_background);
path_value_field_->SetReadOnly(true);
path_value_field_->RemoveBorder();
path_value_field_->SetBackgroundColor(text_area_background);
send_for_value_field_->SetReadOnly(true);
send_for_value_field_->RemoveBorder();
send_for_value_field_->SetBackgroundColor(text_area_background);
created_value_field_->SetReadOnly(true);
created_value_field_->RemoveBorder();
created_value_field_->SetBackgroundColor(text_area_background);
if (expires_value_field_) {
expires_value_field_->SetReadOnly(true);
expires_value_field_->RemoveBorder();
expires_value_field_->SetBackgroundColor(text_area_background);
}
}
<|endoftext|>
|
<commit_before>/*
* Contest2019DataLoader.cpp
*
* Copyright (C) 2019 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "Contest2019DataLoader.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/FilePathParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/IntParam.h"
#include "vislib/sys/Log.h"
using namespace megamol::core;
using namespace megamol::astro;
Contest2019DataLoader::Frame::Frame(view::AnimDataModule& owner) : view::AnimDataModule::Frame(owner) {
// intentionally empty
}
Contest2019DataLoader::Frame::~Frame(void) {
// all the smart pointers are deleted automatically
}
// TODO Frame::loadFrame
bool Contest2019DataLoader::Frame::LoadFrame(std::string filepath, unsigned int frameIdx) { return true; }
void Contest2019DataLoader::Frame::SetData(AstroDataCall& call) {}
// TODO Frame::setData
Contest2019DataLoader::Contest2019DataLoader(void)
: view::AnimDataModule()
, getDataSlot("getData", "Slot for handling the file loading requests")
, firstFilename("firstFilename", "The name of the first file to load")
, filesToLoad("filesToLoad", "The total number of files that should be loaded. A value of -1 means all available "
"ones from the first given are loaded.") {
// TODO setup getDataSlot
this->firstFilename.SetParameter(new param::FilePathParam(""));
this->firstFilename.SetUpdateCallback(&Contest2019DataLoader::filenameChangedCallback);
this->MakeSlotAvailable(&this->firstFilename);
this->filesToLoad.SetParameter(new param::IntParam(-1));
this->MakeSlotAvailable(&this->firstFilename);
this->setFrameCount(1);
this->initFrameCache(1);
}
Contest2019DataLoader::~Contest2019DataLoader(void) { this->Release(); }
view::AnimDataModule::Frame* Contest2019DataLoader::constructFrame(void) const {
Frame* f = new Frame(*const_cast<Contest2019DataLoader*>(this));
return f;
}
bool Contest2019DataLoader::create(void) { return true; }
void Contest2019DataLoader::loadFrame(view::AnimDataModule::Frame* frame, unsigned int idx) {
using vislib::sys::Log;
Frame* f = dynamic_cast<Frame*>(frame);
if (f == nullptr) return;
ASSERT(idx < this->FrameCount());
std::string filename; // TODO determine correct filename and frame idx
unsigned int frameID;
if (!f->LoadFrame(filename, frameID)) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Unable to read frame %d from file\n", idx);
}
}
void Contest2019DataLoader::release(void) { this->resetFrameCache(); }
bool Contest2019DataLoader::filenameChangedCallback(param::ParamSlot& slot) {
// TODO implement
return true;
}
bool Contest2019DataLoader::getDataCallback(Call& caller) {
AstroDataCall* ast = dynamic_cast<AstroDataCall*>(&caller);
if (ast == nullptr) return false;
Frame* f = dynamic_cast<Frame*>(this->requestLockedFrame(ast->FrameID(), ast->IsFrameForced()));
if (f == nullptr) return false;
ast->SetUnlocker(new Unlocker(*f));
ast->SetFrameID(f->FrameNumber());
ast->SetDataHash(this->data_hash);
f->SetData(*ast);
return true;
}
bool Contest2019DataLoader::getExtentCallback(Call& caller) {
AstroDataCall* ast = dynamic_cast<AstroDataCall*>(&caller);
if (ast == nullptr) return false;
ast->SetFrameCount(this->FrameCount());
ast->AccessBoundingBoxes().Clear();
ast->AccessBoundingBoxes().SetObjectSpaceBBox(this->boundingBox);
ast->AccessBoundingBoxes().SetObjectSpaceClipBox(this->clipBox);
ast->SetDataHash(this->data_hash);
return true;
}
<commit_msg>Made connection of the modules possible<commit_after>/*
* Contest2019DataLoader.cpp
*
* Copyright (C) 2019 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "Contest2019DataLoader.h"
#include "astro/AstroDataCall.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/FilePathParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/IntParam.h"
#include "vislib/sys/Log.h"
using namespace megamol::core;
using namespace megamol::astro;
Contest2019DataLoader::Frame::Frame(view::AnimDataModule& owner) : view::AnimDataModule::Frame(owner) {
// intentionally empty
}
Contest2019DataLoader::Frame::~Frame(void) {
// all the smart pointers are deleted automatically
}
// TODO Frame::loadFrame
bool Contest2019DataLoader::Frame::LoadFrame(std::string filepath, unsigned int frameIdx) { return true; }
void Contest2019DataLoader::Frame::SetData(AstroDataCall& call) {}
// TODO Frame::setData
Contest2019DataLoader::Contest2019DataLoader(void)
: view::AnimDataModule()
, getDataSlot("getData", "Slot for handling the file loading requests")
, firstFilename("firstFilename", "The name of the first file to load")
, filesToLoad("filesToLoad", "The total number of files that should be loaded. A value smaller than 0 means all available "
"ones from the first given are loaded.") {
this->getDataSlot.SetCallback(AstroDataCall::ClassName(),
AstroDataCall::FunctionName(AstroDataCall::CallForGetData), &Contest2019DataLoader::getDataCallback);
this->getDataSlot.SetCallback(AstroDataCall::ClassName(),
AstroDataCall::FunctionName(AstroDataCall::CallForGetExtent), &Contest2019DataLoader::getExtentCallback);
this->MakeSlotAvailable(&this->getDataSlot);
this->firstFilename.SetParameter(new param::FilePathParam(""));
this->firstFilename.SetUpdateCallback(&Contest2019DataLoader::filenameChangedCallback);
this->MakeSlotAvailable(&this->firstFilename);
this->filesToLoad.SetParameter(new param::IntParam(-1));
this->MakeSlotAvailable(&this->filesToLoad);
this->setFrameCount(1);
this->initFrameCache(1);
}
Contest2019DataLoader::~Contest2019DataLoader(void) { this->Release(); }
view::AnimDataModule::Frame* Contest2019DataLoader::constructFrame(void) const {
Frame* f = new Frame(*const_cast<Contest2019DataLoader*>(this));
return f;
}
bool Contest2019DataLoader::create(void) { return true; }
void Contest2019DataLoader::loadFrame(view::AnimDataModule::Frame* frame, unsigned int idx) {
using vislib::sys::Log;
Frame* f = dynamic_cast<Frame*>(frame);
if (f == nullptr) return;
ASSERT(idx < this->FrameCount());
std::string filename; // TODO determine correct filename and frame idx
unsigned int frameID;
if (!f->LoadFrame(filename, frameID)) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Unable to read frame %d from file\n", idx);
}
}
void Contest2019DataLoader::release(void) { this->resetFrameCache(); }
bool Contest2019DataLoader::filenameChangedCallback(param::ParamSlot& slot) {
// TODO implement
return true;
}
bool Contest2019DataLoader::getDataCallback(Call& caller) {
AstroDataCall* ast = dynamic_cast<AstroDataCall*>(&caller);
if (ast == nullptr) return false;
Frame* f = dynamic_cast<Frame*>(this->requestLockedFrame(ast->FrameID(), ast->IsFrameForced()));
if (f == nullptr) return false;
ast->SetUnlocker(new Unlocker(*f));
ast->SetFrameID(f->FrameNumber());
ast->SetDataHash(this->data_hash);
f->SetData(*ast);
return true;
}
bool Contest2019DataLoader::getExtentCallback(Call& caller) {
AstroDataCall* ast = dynamic_cast<AstroDataCall*>(&caller);
if (ast == nullptr) return false;
ast->SetFrameCount(this->FrameCount());
ast->AccessBoundingBoxes().Clear();
ast->AccessBoundingBoxes().SetObjectSpaceBBox(this->boundingBox);
ast->AccessBoundingBoxes().SetObjectSpaceClipBox(this->clipBox);
ast->SetDataHash(this->data_hash);
return true;
}
<|endoftext|>
|
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2007 Bruno Virlet <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "kotimespentview.h"
#include "koglobals.h"
#include "koprefs.h"
#include <kcal/calendar.h>
#include <kcal/event.h>
#include <QDate>
#include <QMap>
#include <QBoxLayout>
#include <QPainter>
#include <QPainterPath>
class TimeSpentWidget : public QWidget
{
public:
TimeSpentWidget( KOTimeSpentView *parent )
: QWidget( parent ), mTimeSpentView( parent ) {}
~TimeSpentWidget() {}
void paintEvent( QPaintEvent *e )
{
QPainter p( this );
p.fillRect( e->rect(), Qt::white );
int margin = 10;
int y = 90;
p.fillRect( QRect( 5, 5, width(), 35 ), QColor( 54, 121, 173 ) ); // sync with kowhatsnextview
QPen oldPen = p.pen();
QFont oldFont = p.font();
QFont font = p.font();
font.setPixelSize( 25 );
font.setBold( true );
p.setFont( font );
p.setPen( QColor( Qt::white ) );
p.drawText( QPoint( 25, 35 ), i18n( "Time Tracker" ) );
p.setPen( oldPen );
p.setFont( oldFont );
QString dateText;
if ( mTimeSpentView->mStartDate.daysTo( mTimeSpentView->mEndDate ) < 1 ) {
dateText = KGlobal::locale()->formatDate( mTimeSpentView->mStartDate );
} else {
dateText = i18nc( "Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mTimeSpentView->mStartDate ),
KGlobal::locale()->formatDate( mTimeSpentView->mEndDate ) );
}
font.setPixelSize( 20 );
font.setBold( true );
p.setFont( font );
p.drawText( QPoint( margin, 60 ), dateText );
p.setPen( oldPen );
p.setFont( oldFont );
QMap<QString, int> secondsSpent;
int total = 0;
foreach ( Event *e, mEventList ) {
if ( e->categories().count() ) {
foreach ( const QString &s, e->categories() ) {
secondsSpent[ s ] += e->dtStart().secsTo( e->dtEnd() );
}
} else {
secondsSpent[ i18n( "No category" ) ] += e->dtStart().secsTo( e->dtEnd() );
}
total += e->dtStart().secsTo( e->dtEnd() );
}
QMapIterator<QString, int> i( secondsSpent );
QFontMetrics fm = p.fontMetrics();
int lineHeight = fm.boundingRect( "No category" ).height();
int totalLineHeight = lineHeight + 2; // vertical margin included
while ( i.hasNext() ) {
i.next();
// bar
QColor color = KOPrefs::instance()->categoryColor( i.key() );
int length = static_cast<int>( ( (double) i.value() ) / total * ( width() - 3 * margin ) );
QPainterPath path( QPoint( margin, y ) );
path.lineTo( margin + length, y );
if ( length < margin ) {
path.lineTo( margin + length, y + lineHeight );
} else {
path.arcTo( QRect( margin + length, y, 2 * margin, lineHeight ), +90, -180 );
}
path.lineTo( margin, y + lineHeight );
path.closeSubpath();
p.setBrush( color );
p.drawPath( path );
// text
int totHr, perHr;
if ( total > 0 ) {
totHr = i.value() / ( 60 * 60 );
perHr = static_cast<int>( ( (double) i.value() * 100 / total ) );
} else {
totHr = 0;
perHr = 0;
}
p.drawText( QRect( margin + 2, y + 2, width() - 2 * margin, lineHeight ),
i.key() + ": " +
i18ncp( "number of hours spent", "%1 hour", "%1 hours", totHr ) +
i18nc( "percent of hours spent", " (%1%)", perHr ) );
y += totalLineHeight;
}
}
Event::List mEventList;
KOTimeSpentView *mTimeSpentView;
};
KOTimeSpentView::KOTimeSpentView( Calendar *calendar, QWidget *parent )
: KOrg::BaseView( calendar, parent )
{
mView = new TimeSpentWidget( this );
QBoxLayout *topLayout = new QVBoxLayout( this );
topLayout->addWidget( mView );
}
KOTimeSpentView::~KOTimeSpentView()
{
}
int KOTimeSpentView::currentDateCount()
{
return mStartDate.daysTo( mEndDate );
}
void KOTimeSpentView::showDates( const QDate &start, const QDate &end )
{
mStartDate = start;
mEndDate = end;
updateView();
}
void KOTimeSpentView::showIncidences( const Incidence::List & )
{
}
void KOTimeSpentView::changeIncidenceDisplay( Incidence *, int action )
{
switch( action ) {
case KOGlobals::INCIDENCEADDED:
case KOGlobals::INCIDENCEEDITED:
case KOGlobals::INCIDENCEDELETED:
updateView();
break;
default:
break;
}
}
void KOTimeSpentView::updateView()
{
/*
QString text;
text = "<table width=\"100%\">\n";
text += "<tr bgcolor=\"#3679AD\"><td><h1>";
text += "<img src=\"";
// text += todo: put something there.
text += "\">";
text += "<font color=\"white\"> ";
text += i18n("Time tracker") + "</font></h1>";
text += "</td></tr>\n<tr><td>";
text += "<h2>";
if ( mStartDate.daysTo( mEndDate ) < 1 ) {
text += KGlobal::locale()->formatDate( mStartDate );
} else {
text += i18nc("Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mStartDate ) ,
KGlobal::locale()->formatDate( mEndDate ) );
}
text+="</h2>\n";
*/
Event::List events;
KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();
for ( QDate date = mStartDate; date <= mEndDate; date = date.addDays( 1 ) ) {
events += calendar()->events( date, timeSpec,
EventSortStartDate, SortDirectionAscending );
}
mView->mEventList = events;
mView->repaint();
}
<commit_msg>backport SVN commit 938647 by smartins:<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2007 Bruno Virlet <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "kotimespentview.h"
#include "koglobals.h"
#include "koprefs.h"
#include <kcal/calendar.h>
#include <kcal/event.h>
#include <QDate>
#include <QMap>
#include <QBoxLayout>
#include <QPainter>
#include <QPainterPath>
class TimeSpentWidget : public QWidget
{
public:
TimeSpentWidget( KOTimeSpentView *parent )
: QWidget( parent ), mTimeSpentView( parent ) {}
~TimeSpentWidget() {}
void paintEvent( QPaintEvent *e )
{
QPainter p( this );
p.fillRect( e->rect(), Qt::white );
int margin = 10;
int y = 90;
p.fillRect( QRect( 5, 5, width(), 35 ), QColor( 54, 121, 173 ) ); // sync with kowhatsnextview
QPen oldPen = p.pen();
QFont oldFont = p.font();
QFont font = p.font();
font.setPixelSize( 25 );
font.setBold( true );
p.setFont( font );
p.setPen( QColor( Qt::white ) );
p.drawText( QPoint( 25, 35 ), i18n( "Time Tracker" ) );
p.setPen( oldPen );
p.setFont( oldFont );
QString dateText;
if ( mTimeSpentView->mStartDate.daysTo( mTimeSpentView->mEndDate ) < 1 ) {
dateText = KGlobal::locale()->formatDate( mTimeSpentView->mStartDate );
} else {
dateText = i18nc( "Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mTimeSpentView->mStartDate ),
KGlobal::locale()->formatDate( mTimeSpentView->mEndDate ) );
}
font.setPixelSize( 20 );
font.setBold( true );
p.setFont( font );
p.drawText( QPoint( margin, 60 ), dateText );
p.setPen( oldPen );
p.setFont( oldFont );
QMap<QString, int> secondsSpent;
int total = 0;
foreach ( Event *e, mEventList ) {
KDateTime selectedStart( mTimeSpentView->mStartDate,
QTime( 0, 0 ),
e->dtStart().timeSpec() );
KDateTime selectedEnd( mTimeSpentView->mEndDate.addDays( 1 ),
QTime( 0, 0 ),
e->dtEnd().timeSpec() );
KDateTime start;
KDateTime end;
// duration of all occurrences added
int totalDuration = 0;
if ( e->recurs() ) {
int eventDuration = e->dtStart().secsTo( e->dtEnd() );
// timesInInterval only return events that have their start inside the interval
// so we resize the interval by -eventDuration
DateTimeList times = e->recurrence()->timesInInterval( selectedStart.addSecs( -eventDuration ), selectedEnd );
foreach ( KDateTime kdt, times ) {
// either the event's start or the event's end must be in the view's interval
if ( kdt >= selectedStart ||
kdt.addSecs( eventDuration ) >= selectedStart ) {
start = kdt > selectedStart ? kdt : selectedStart;
end = kdt.addSecs( eventDuration ) < selectedEnd ? kdt.addSecs( eventDuration ) : selectedEnd;
totalDuration += start.secsTo( end );
}
}
} else {
// The event's start can be before the view's start date or end after the view's end
start = e->dtStart() > selectedStart ? e->dtStart() : selectedStart;
end = e->dtEnd() < selectedEnd ? e->dtEnd() : selectedEnd;
totalDuration += start.secsTo( end );
}
if ( totalDuration == 0 ) {
continue;
}
if ( e->categories().count() ) {
foreach ( const QString &s, e->categories() ) {
secondsSpent[ s ] += totalDuration;
}
} else {
secondsSpent[ i18n( "No category" ) ] += totalDuration;
}
total += totalDuration;
}
QMapIterator<QString, int> i( secondsSpent );
QFontMetrics fm = p.fontMetrics();
int lineHeight = fm.boundingRect( "No category" ).height();
int totalLineHeight = lineHeight + 2; // vertical margin included
while ( i.hasNext() ) {
i.next();
// bar
QColor color = KOPrefs::instance()->categoryColor( i.key() );
int length = static_cast<int>( ( (double) i.value() ) / total * ( width() - 3 * margin ) );
QPainterPath path( QPoint( margin, y ) );
path.lineTo( margin + length, y );
if ( length < margin ) {
path.lineTo( margin + length, y + lineHeight );
} else {
path.arcTo( QRect( margin + length, y, 2 * margin, lineHeight ), +90, -180 );
}
path.lineTo( margin, y + lineHeight );
path.closeSubpath();
p.setBrush( color );
p.drawPath( path );
// text
int totHr, perHr;
if ( total > 0 ) {
totHr = i.value() / ( 60 * 60 );
perHr = static_cast<int>( ( (double) i.value() * 100 / total ) );
} else {
totHr = 0;
perHr = 0;
}
p.drawText( QRect( margin + 2, y + 2, width() - 2 * margin, lineHeight ),
i.key() + ": " +
i18ncp( "number of hours spent", "%1 hour", "%1 hours", totHr ) +
i18nc( "percent of hours spent", " (%1%)", perHr ) );
y += totalLineHeight;
}
}
Event::List mEventList;
KOTimeSpentView *mTimeSpentView;
};
KOTimeSpentView::KOTimeSpentView( Calendar *calendar, QWidget *parent )
: KOrg::BaseView( calendar, parent )
{
mView = new TimeSpentWidget( this );
QBoxLayout *topLayout = new QVBoxLayout( this );
topLayout->addWidget( mView );
}
KOTimeSpentView::~KOTimeSpentView()
{
}
int KOTimeSpentView::currentDateCount()
{
return mStartDate.daysTo( mEndDate );
}
void KOTimeSpentView::showDates( const QDate &start, const QDate &end )
{
mStartDate = start;
mEndDate = end;
updateView();
}
void KOTimeSpentView::showIncidences( const Incidence::List & )
{
}
void KOTimeSpentView::changeIncidenceDisplay( Incidence *, int action )
{
switch( action ) {
case KOGlobals::INCIDENCEADDED:
case KOGlobals::INCIDENCEEDITED:
case KOGlobals::INCIDENCEDELETED:
updateView();
break;
default:
break;
}
}
void KOTimeSpentView::updateView()
{
/*
QString text;
text = "<table width=\"100%\">\n";
text += "<tr bgcolor=\"#3679AD\"><td><h1>";
text += "<img src=\"";
// text += todo: put something there.
text += "\">";
text += "<font color=\"white\"> ";
text += i18n("Time tracker") + "</font></h1>";
text += "</td></tr>\n<tr><td>";
text += "<h2>";
if ( mStartDate.daysTo( mEndDate ) < 1 ) {
text += KGlobal::locale()->formatDate( mStartDate );
} else {
text += i18nc("Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mStartDate ) ,
KGlobal::locale()->formatDate( mEndDate ) );
}
text+="</h2>\n";
*/
KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();
mView->mEventList = calendar()->events( mStartDate, mEndDate, timeSpec );
mView->repaint();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/website_settings_model.h"
#include <string>
#include <vector>
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ssl/ssl_error_info.h"
#include "content/browser/cert_store.h"
#include "content/public/common/ssl_status.h"
#include "content/public/common/url_constants.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/cert_status_flags.h"
#include "net/base/ssl_cipher_suite_names.h"
#include "net/base/ssl_connection_status_flags.h"
#include "net/base/x509_certificate.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
WebsiteSettingsModel::WebsiteSettingsModel(Profile* profile,
const GURL& url,
const content::SSLStatus& ssl,
CertStore* cert_store)
: site_identity_status_(SITE_IDENTITY_STATUS_UNKNOWN),
site_connection_status_(SITE_CONNECTION_STATUS_UNKNOWN),
cert_store_(cert_store) {
Init(profile, url, ssl);
// After initialization the status about the site's connection
// and it's identity must be available.
DCHECK_NE(site_identity_status_, SITE_IDENTITY_STATUS_UNKNOWN);
DCHECK_NE(site_connection_status_, SITE_CONNECTION_STATUS_UNKNOWN);
}
WebsiteSettingsModel::~WebsiteSettingsModel() {
}
void WebsiteSettingsModel::Init(Profile* profile,
const GURL& url,
const content::SSLStatus& ssl) {
if (url.SchemeIs(chrome::kChromeUIScheme)) {
site_identity_status_ = SITE_IDENTITY_STATUS_INTERNAL_PAGE;
site_identity_details_ =
l10n_util::GetStringUTF16(IDS_PAGE_INFO_INTERNAL_PAGE);
site_connection_status_ = SITE_CONNECTION_STATUS_INTERNAL_PAGE;
return;
}
scoped_refptr<net::X509Certificate> cert;
// Identity section.
string16 subject_name(UTF8ToUTF16(url.host()));
bool empty_subject_name = false;
if (subject_name.empty()) {
subject_name.assign(
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
empty_subject_name = true;
}
if (ssl.cert_id &&
cert_store_->RetrieveCert(ssl.cert_id, &cert) &&
(!net::IsCertStatusError(ssl.cert_status) ||
net::IsCertStatusMinorError(ssl.cert_status))) {
// There are no major errors. Check for minor errors.
if (net::IsCertStatusMinorError(ssl.cert_status)) {
site_identity_status_ = SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN;
string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
site_identity_details_ += ASCIIToUTF16("\n\n");
if (ssl.cert_status & net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) {
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION);
} else if (ssl.cert_status & net::CERT_STATUS_NO_REVOCATION_MECHANISM) {
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_REVOCATION_MECHANISM);
} else {
NOTREACHED() << "Need to specify string for this warning";
}
} else if (ssl.cert_status & net::CERT_STATUS_IS_EV) {
// EV HTTPS page.
site_identity_status_ = SITE_IDENTITY_STATUS_EV_CERT;
DCHECK(!cert->subject().organization_names.empty());
organization_name_ = UTF8ToUTF16(cert->subject().organization_names[0]);
// An EV Cert is required to have a city (localityName) and country but
// state is "if any".
DCHECK(!cert->subject().locality_name.empty());
DCHECK(!cert->subject().country_name.empty());
string16 locality;
if (!cert->subject().state_or_province_name.empty()) {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().state_or_province_name),
UTF8ToUTF16(cert->subject().country_name));
} else {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_PARTIAL_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().country_name));
}
DCHECK(!cert->subject().organization_names.empty());
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
UTF8ToUTF16(cert->subject().organization_names[0]),
locality,
UTF8ToUTF16(cert->issuer().GetDisplayName())));
} else if (ssl.cert_status & net::CERT_STATUS_IS_DNSSEC) {
// DNSSEC authenticated page.
site_identity_status_ = SITE_IDENTITY_STATUS_DNSSEC_CERT;
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, UTF8ToUTF16("DNSSEC")));
} else {
// Non-EV OK HTTPS page.
site_identity_status_ = SITE_IDENTITY_STATUS_CERT;
string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
}
} else {
// HTTP or HTTPS with errors (not warnings).
site_identity_details_.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
if (ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED)
site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT;
else
site_identity_status_ = SITE_IDENTITY_STATUS_ERROR;
const string16 bullet = UTF8ToUTF16("\n • ");
std::vector<SSLErrorInfo> errors;
SSLErrorInfo::GetErrorsForCertStatus(ssl.cert_id, ssl.cert_status,
url, &errors);
for (size_t i = 0; i < errors.size(); ++i) {
site_identity_details_ += bullet;
site_identity_details_ += errors[i].short_description();
}
if (ssl.cert_status & net::CERT_STATUS_NON_UNIQUE_NAME) {
site_identity_details_ += ASCIIToUTF16("\n\n");
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME);
}
}
// Site Connection
// We consider anything less than 80 bits encryption to be weak encryption.
// TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
// weakly encrypted connections.
site_connection_status_ = SITE_CONNECTION_STATUS_UNKNOWN;
if (!ssl.cert_id) {
// Not HTTPS.
DCHECK_EQ(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED);
if (ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED)
site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED;
else
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits < 0) {
// Security strength is unknown. Say nothing.
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
} else if (ssl.security_bits == 0) {
DCHECK_NE(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED);
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits < 80) {
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
subject_name));
} else {
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
subject_name,
base::IntToString16(ssl.security_bits)));
if (ssl.content_status) {
bool ran_insecure_content =
!!(ssl.content_status & content::SSLStatus::RAN_INSECURE_CONTENT);
site_connection_status_ = ran_insecure_content ?
SITE_CONNECTION_STATUS_ENCRYPTED_ERROR
: SITE_CONNECTION_STATUS_MIXED_CONTENT;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
site_connection_details_,
l10n_util::GetStringUTF16(ran_insecure_content ?
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));
}
}
uint16 cipher_suite =
net::SSLConnectionStatusToCipherSuite(ssl.connection_status);
if (ssl.security_bits > 0 && cipher_suite) {
int ssl_version =
net::SSLConnectionStatusToVersion(ssl.connection_status);
const char* ssl_version_str;
net::SSLVersionToString(&ssl_version_str, ssl_version);
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION,
ASCIIToUTF16(ssl_version_str));
bool did_fallback = (ssl.connection_status &
net::SSL_CONNECTION_SSL3_FALLBACK) != 0;
bool no_renegotiation =
(ssl.connection_status &
net::SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION) != 0;
const char *key_exchange, *cipher, *mac;
net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, cipher_suite);
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS,
ASCIIToUTF16(cipher), ASCIIToUTF16(mac), ASCIIToUTF16(key_exchange));
site_connection_details_ += ASCIIToUTF16("\n\n");
uint8 compression_id =
net::SSLConnectionStatusToCompression(ssl.connection_status);
if (compression_id) {
const char* compression;
net::SSLCompressionToString(&compression, compression_id);
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_COMPRESSION_DETAILS,
ASCIIToUTF16(compression));
} else {
site_connection_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_COMPRESSION);
}
if (did_fallback) {
// For now, only SSLv3 fallback will trigger a warning icon.
if (site_connection_status_ < SITE_CONNECTION_STATUS_MIXED_CONTENT)
site_connection_status_ = SITE_CONNECTION_STATUS_MIXED_CONTENT;
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_FALLBACK_MESSAGE);
}
if (no_renegotiation) {
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_RENEGOTIATION_MESSAGE);
}
}
}
<commit_msg>Remove unused variable empty_subject_name.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/website_settings_model.h"
#include <string>
#include <vector>
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ssl/ssl_error_info.h"
#include "content/browser/cert_store.h"
#include "content/public/common/ssl_status.h"
#include "content/public/common/url_constants.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/cert_status_flags.h"
#include "net/base/ssl_cipher_suite_names.h"
#include "net/base/ssl_connection_status_flags.h"
#include "net/base/x509_certificate.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
WebsiteSettingsModel::WebsiteSettingsModel(Profile* profile,
const GURL& url,
const content::SSLStatus& ssl,
CertStore* cert_store)
: site_identity_status_(SITE_IDENTITY_STATUS_UNKNOWN),
site_connection_status_(SITE_CONNECTION_STATUS_UNKNOWN),
cert_store_(cert_store) {
Init(profile, url, ssl);
// After initialization the status about the site's connection
// and it's identity must be available.
DCHECK_NE(site_identity_status_, SITE_IDENTITY_STATUS_UNKNOWN);
DCHECK_NE(site_connection_status_, SITE_CONNECTION_STATUS_UNKNOWN);
}
WebsiteSettingsModel::~WebsiteSettingsModel() {
}
void WebsiteSettingsModel::Init(Profile* profile,
const GURL& url,
const content::SSLStatus& ssl) {
if (url.SchemeIs(chrome::kChromeUIScheme)) {
site_identity_status_ = SITE_IDENTITY_STATUS_INTERNAL_PAGE;
site_identity_details_ =
l10n_util::GetStringUTF16(IDS_PAGE_INFO_INTERNAL_PAGE);
site_connection_status_ = SITE_CONNECTION_STATUS_INTERNAL_PAGE;
return;
}
scoped_refptr<net::X509Certificate> cert;
// Identity section.
string16 subject_name(UTF8ToUTF16(url.host()));
if (subject_name.empty()) {
subject_name.assign(
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
if (ssl.cert_id &&
cert_store_->RetrieveCert(ssl.cert_id, &cert) &&
(!net::IsCertStatusError(ssl.cert_status) ||
net::IsCertStatusMinorError(ssl.cert_status))) {
// There are no major errors. Check for minor errors.
if (net::IsCertStatusMinorError(ssl.cert_status)) {
site_identity_status_ = SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN;
string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
site_identity_details_ += ASCIIToUTF16("\n\n");
if (ssl.cert_status & net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) {
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION);
} else if (ssl.cert_status & net::CERT_STATUS_NO_REVOCATION_MECHANISM) {
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_REVOCATION_MECHANISM);
} else {
NOTREACHED() << "Need to specify string for this warning";
}
} else if (ssl.cert_status & net::CERT_STATUS_IS_EV) {
// EV HTTPS page.
site_identity_status_ = SITE_IDENTITY_STATUS_EV_CERT;
DCHECK(!cert->subject().organization_names.empty());
organization_name_ = UTF8ToUTF16(cert->subject().organization_names[0]);
// An EV Cert is required to have a city (localityName) and country but
// state is "if any".
DCHECK(!cert->subject().locality_name.empty());
DCHECK(!cert->subject().country_name.empty());
string16 locality;
if (!cert->subject().state_or_province_name.empty()) {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().state_or_province_name),
UTF8ToUTF16(cert->subject().country_name));
} else {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_PARTIAL_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().country_name));
}
DCHECK(!cert->subject().organization_names.empty());
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
UTF8ToUTF16(cert->subject().organization_names[0]),
locality,
UTF8ToUTF16(cert->issuer().GetDisplayName())));
} else if (ssl.cert_status & net::CERT_STATUS_IS_DNSSEC) {
// DNSSEC authenticated page.
site_identity_status_ = SITE_IDENTITY_STATUS_DNSSEC_CERT;
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, UTF8ToUTF16("DNSSEC")));
} else {
// Non-EV OK HTTPS page.
site_identity_status_ = SITE_IDENTITY_STATUS_CERT;
string16 issuer_name(UTF8ToUTF16(cert->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
}
} else {
// HTTP or HTTPS with errors (not warnings).
site_identity_details_.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
if (ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED)
site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT;
else
site_identity_status_ = SITE_IDENTITY_STATUS_ERROR;
const string16 bullet = UTF8ToUTF16("\n • ");
std::vector<SSLErrorInfo> errors;
SSLErrorInfo::GetErrorsForCertStatus(ssl.cert_id, ssl.cert_status,
url, &errors);
for (size_t i = 0; i < errors.size(); ++i) {
site_identity_details_ += bullet;
site_identity_details_ += errors[i].short_description();
}
if (ssl.cert_status & net::CERT_STATUS_NON_UNIQUE_NAME) {
site_identity_details_ += ASCIIToUTF16("\n\n");
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME);
}
}
// Site Connection
// We consider anything less than 80 bits encryption to be weak encryption.
// TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
// weakly encrypted connections.
site_connection_status_ = SITE_CONNECTION_STATUS_UNKNOWN;
if (!ssl.cert_id) {
// Not HTTPS.
DCHECK_EQ(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED);
if (ssl.security_style == content::SECURITY_STYLE_UNAUTHENTICATED)
site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED;
else
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits < 0) {
// Security strength is unknown. Say nothing.
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
} else if (ssl.security_bits == 0) {
DCHECK_NE(ssl.security_style, content::SECURITY_STYLE_UNAUTHENTICATED);
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits < 80) {
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
subject_name));
} else {
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
subject_name,
base::IntToString16(ssl.security_bits)));
if (ssl.content_status) {
bool ran_insecure_content =
!!(ssl.content_status & content::SSLStatus::RAN_INSECURE_CONTENT);
site_connection_status_ = ran_insecure_content ?
SITE_CONNECTION_STATUS_ENCRYPTED_ERROR
: SITE_CONNECTION_STATUS_MIXED_CONTENT;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
site_connection_details_,
l10n_util::GetStringUTF16(ran_insecure_content ?
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));
}
}
uint16 cipher_suite =
net::SSLConnectionStatusToCipherSuite(ssl.connection_status);
if (ssl.security_bits > 0 && cipher_suite) {
int ssl_version =
net::SSLConnectionStatusToVersion(ssl.connection_status);
const char* ssl_version_str;
net::SSLVersionToString(&ssl_version_str, ssl_version);
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION,
ASCIIToUTF16(ssl_version_str));
bool did_fallback = (ssl.connection_status &
net::SSL_CONNECTION_SSL3_FALLBACK) != 0;
bool no_renegotiation =
(ssl.connection_status &
net::SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION) != 0;
const char *key_exchange, *cipher, *mac;
net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, cipher_suite);
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS,
ASCIIToUTF16(cipher), ASCIIToUTF16(mac), ASCIIToUTF16(key_exchange));
site_connection_details_ += ASCIIToUTF16("\n\n");
uint8 compression_id =
net::SSLConnectionStatusToCompression(ssl.connection_status);
if (compression_id) {
const char* compression;
net::SSLCompressionToString(&compression, compression_id);
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_COMPRESSION_DETAILS,
ASCIIToUTF16(compression));
} else {
site_connection_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_COMPRESSION);
}
if (did_fallback) {
// For now, only SSLv3 fallback will trigger a warning icon.
if (site_connection_status_ < SITE_CONNECTION_STATUS_MIXED_CONTENT)
site_connection_status_ = SITE_CONNECTION_STATUS_MIXED_CONTENT;
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_FALLBACK_MESSAGE);
}
if (no_renegotiation) {
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_RENEGOTIATION_MESSAGE);
}
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2007 Bruno Virlet <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "kotimespentview.h"
#include "koglobals.h"
#include "koprefs.h"
#include <kcal/calendar.h>
#include <kcal/event.h>
#include <QDate>
#include <QMap>
#include <QBoxLayout>
#include <QPainter>
#include <QPainterPath>
class TimeSpentWidget : public QWidget
{
public:
TimeSpentWidget( KOTimeSpentView *parent )
: QWidget( parent ), mTimeSpentView( parent ) {}
~TimeSpentWidget() {}
void paintEvent( QPaintEvent *e )
{
QPainter p( this );
p.fillRect( e->rect(), Qt::white );
int margin = 10;
int y = 90;
p.fillRect( QRect( 5, 5, width(), 35 ), QColor( 54, 121, 173 ) ); // sync with kowhatsnextview
QPen oldPen = p.pen();
QFont oldFont = p.font();
QFont font = p.font();
font.setPixelSize( 25 );
font.setBold( true );
p.setFont( font );
p.setPen( QColor( Qt::white ) );
p.drawText( QPoint( 25, 35 ), i18n( "Time Tracker" ) );
p.setPen( oldPen );
p.setFont( oldFont );
QString dateText;
if ( mTimeSpentView->mStartDate.daysTo( mTimeSpentView->mEndDate ) < 1 ) {
dateText = KGlobal::locale()->formatDate( mTimeSpentView->mStartDate );
} else {
dateText = i18nc( "Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mTimeSpentView->mStartDate ),
KGlobal::locale()->formatDate( mTimeSpentView->mEndDate ) );
}
font.setPixelSize( 20 );
font.setBold( true );
p.setFont( font );
p.drawText( QPoint( margin, 60 ), dateText );
p.setPen( oldPen );
p.setFont( oldFont );
QMap<QString, int> secondsSpent;
int total = 0;
foreach ( Event *e, mEventList ) {
if ( e->categories().count() ) {
foreach ( const QString &s, e->categories() ) {
secondsSpent[ s ] += e->dtStart().secsTo( e->dtEnd() );
}
} else {
secondsSpent[ i18n( "No category" ) ] += e->dtStart().secsTo( e->dtEnd() );
}
total += e->dtStart().secsTo( e->dtEnd() );
}
QMapIterator<QString, int> i( secondsSpent );
QFontMetrics fm = p.fontMetrics();
int lineHeight = fm.boundingRect( "No category" ).height();
int totalLineHeight = lineHeight + 2; // vertical margin included
while ( i.hasNext() ) {
i.next();
// bar
QColor color = KOPrefs::instance()->categoryColor( i.key() );
int length = static_cast<int>( ( (double) i.value() ) / total * ( width() - 3 * margin ) );
QPainterPath path( QPoint( margin, y ) );
path.lineTo( margin + length, y );
if ( length < margin ) {
path.lineTo( margin + length, y + lineHeight );
} else {
path.arcTo( QRect( margin + length, y, 2 * margin, lineHeight ), +90, -180 );
}
path.lineTo( margin, y + lineHeight );
path.closeSubpath();
p.setBrush( color );
p.drawPath( path );
// text
int totHr, perHr;
if ( total > 0 ) {
totHr = i.value() / ( 60 * 60 );
perHr = static_cast<int>( ( (double) i.value() * 100 / total ) );
} else {
totHr = 0;
perHr = 0;
}
p.drawText( QRect( margin + 2, y + 2, width() - 2 * margin, lineHeight ),
i.key() + ": " +
i18ncp( "number of hours spent", "%1 hour", "%1 hours", totHr ) +
i18nc( "percent of hours spent", " (%1%)", perHr ) );
y += totalLineHeight;
}
}
Event::List mEventList;
KOTimeSpentView *mTimeSpentView;
};
KOTimeSpentView::KOTimeSpentView( Calendar *calendar, QWidget *parent )
: KOrg::BaseView( calendar, parent )
{
mView = new TimeSpentWidget( this );
QBoxLayout *topLayout = new QVBoxLayout( this );
topLayout->addWidget( mView );
}
KOTimeSpentView::~KOTimeSpentView()
{
}
int KOTimeSpentView::currentDateCount()
{
return mStartDate.daysTo( mEndDate );
}
void KOTimeSpentView::showDates( const QDate &start, const QDate &end )
{
mStartDate = start;
mEndDate = end;
updateView();
}
void KOTimeSpentView::showIncidences( const Incidence::List & )
{
}
void KOTimeSpentView::changeIncidenceDisplay( Incidence *, int action )
{
switch( action ) {
case KOGlobals::INCIDENCEADDED:
case KOGlobals::INCIDENCEEDITED:
case KOGlobals::INCIDENCEDELETED:
updateView();
break;
default:
break;
}
}
void KOTimeSpentView::updateView()
{
/*
QString text;
text = "<table width=\"100%\">\n";
text += "<tr bgcolor=\"#3679AD\"><td><h1>";
text += "<img src=\"";
// text += todo: put something there.
text += "\">";
text += "<font color=\"white\"> ";
text += i18n("Time tracker") + "</font></h1>";
text += "</td></tr>\n<tr><td>";
text += "<h2>";
if ( mStartDate.daysTo( mEndDate ) < 1 ) {
text += KGlobal::locale()->formatDate( mStartDate );
} else {
text += i18nc("Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mStartDate ) ,
KGlobal::locale()->formatDate( mEndDate ) );
}
text+="</h2>\n";
*/
Event::List events;
KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();
for ( QDate date = mStartDate; date <= mEndDate; date = date.addDays( 1 ) ) {
events += calendar()->events( date, timeSpec,
EventSortStartDate, SortDirectionAscending );
}
mView->mEventList = events;
mView->repaint();
}
<commit_msg>Multiday events are now properly counted (recurring and non recurring).<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2007 Bruno Virlet <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "kotimespentview.h"
#include "koglobals.h"
#include "koprefs.h"
#include <kcal/calendar.h>
#include <kcal/event.h>
#include <QDate>
#include <QMap>
#include <QBoxLayout>
#include <QPainter>
#include <QPainterPath>
class TimeSpentWidget : public QWidget
{
public:
TimeSpentWidget( KOTimeSpentView *parent )
: QWidget( parent ), mTimeSpentView( parent ) {}
~TimeSpentWidget() {}
void paintEvent( QPaintEvent *e )
{
QPainter p( this );
p.fillRect( e->rect(), Qt::white );
int margin = 10;
int y = 90;
p.fillRect( QRect( 5, 5, width(), 35 ), QColor( 54, 121, 173 ) ); // sync with kowhatsnextview
QPen oldPen = p.pen();
QFont oldFont = p.font();
QFont font = p.font();
font.setPixelSize( 25 );
font.setBold( true );
p.setFont( font );
p.setPen( QColor( Qt::white ) );
p.drawText( QPoint( 25, 35 ), i18n( "Time Tracker" ) );
p.setPen( oldPen );
p.setFont( oldFont );
QString dateText;
if ( mTimeSpentView->mStartDate.daysTo( mTimeSpentView->mEndDate ) < 1 ) {
dateText = KGlobal::locale()->formatDate( mTimeSpentView->mStartDate );
} else {
dateText = i18nc( "Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mTimeSpentView->mStartDate ),
KGlobal::locale()->formatDate( mTimeSpentView->mEndDate ) );
}
font.setPixelSize( 20 );
font.setBold( true );
p.setFont( font );
p.drawText( QPoint( margin, 60 ), dateText );
p.setPen( oldPen );
p.setFont( oldFont );
QMap<QString, int> secondsSpent;
int total = 0;
foreach ( Event *e, mEventList ) {
KDateTime selectedStart( mTimeSpentView->mStartDate,
QTime( 0, 0 ),
e->dtStart().timeSpec() );
KDateTime selectedEnd( mTimeSpentView->mEndDate.addDays( 1 ),
QTime( 0, 0 ),
e->dtEnd().timeSpec() );
KDateTime start;
KDateTime end;
// duration of all occurrences added
int totalDuration = 0;
if ( e->recurs() ) {
int eventDuration = e->dtStart().secsTo( e->dtEnd() );
// timesInInterval only return events that have their start inside the interval
// so we resize the interval by -eventDuration
DateTimeList times = e->recurrence()->timesInInterval( selectedStart.addSecs( -eventDuration ), selectedEnd );
foreach ( KDateTime kdt, times ) {
// either the event's start or the event's end must be in the view's interval
if ( kdt >= selectedStart ||
kdt.addSecs( eventDuration ) >= selectedStart ) {
start = kdt > selectedStart ? kdt : selectedStart;
end = kdt.addSecs( eventDuration ) < selectedEnd ? kdt.addSecs( eventDuration ) : selectedEnd;
totalDuration += start.secsTo( end );
}
}
} else {
// The event's start can be before the view's start date or end after the view's end
start = e->dtStart() > selectedStart ? e->dtStart() : selectedStart;
end = e->dtEnd() < selectedEnd ? e->dtEnd() : selectedEnd;
totalDuration += start.secsTo( end );
}
if ( totalDuration == 0 ) {
continue;
}
if ( e->categories().count() ) {
foreach ( const QString &s, e->categories() ) {
secondsSpent[ s ] += totalDuration;
}
} else {
secondsSpent[ i18n( "No category" ) ] += totalDuration;
}
total += totalDuration;
}
QMapIterator<QString, int> i( secondsSpent );
QFontMetrics fm = p.fontMetrics();
int lineHeight = fm.boundingRect( "No category" ).height();
int totalLineHeight = lineHeight + 2; // vertical margin included
while ( i.hasNext() ) {
i.next();
// bar
QColor color = KOPrefs::instance()->categoryColor( i.key() );
int length = static_cast<int>( ( (double) i.value() ) / total * ( width() - 3 * margin ) );
QPainterPath path( QPoint( margin, y ) );
path.lineTo( margin + length, y );
if ( length < margin ) {
path.lineTo( margin + length, y + lineHeight );
} else {
path.arcTo( QRect( margin + length, y, 2 * margin, lineHeight ), +90, -180 );
}
path.lineTo( margin, y + lineHeight );
path.closeSubpath();
p.setBrush( color );
p.drawPath( path );
// text
int totHr, perHr;
if ( total > 0 ) {
totHr = i.value() / ( 60 * 60 );
perHr = static_cast<int>( ( (double) i.value() * 100 / total ) );
} else {
totHr = 0;
perHr = 0;
}
p.drawText( QRect( margin + 2, y + 2, width() - 2 * margin, lineHeight ),
i.key() + ": " +
i18ncp( "number of hours spent", "%1 hour", "%1 hours", totHr ) +
i18nc( "percent of hours spent", " (%1%)", perHr ) );
y += totalLineHeight;
}
}
Event::List mEventList;
KOTimeSpentView *mTimeSpentView;
};
KOTimeSpentView::KOTimeSpentView( Calendar *calendar, QWidget *parent )
: KOrg::BaseView( calendar, parent )
{
mView = new TimeSpentWidget( this );
QBoxLayout *topLayout = new QVBoxLayout( this );
topLayout->addWidget( mView );
}
KOTimeSpentView::~KOTimeSpentView()
{
}
int KOTimeSpentView::currentDateCount()
{
return mStartDate.daysTo( mEndDate );
}
void KOTimeSpentView::showDates( const QDate &start, const QDate &end )
{
mStartDate = start;
mEndDate = end;
updateView();
}
void KOTimeSpentView::showIncidences( const Incidence::List & )
{
}
void KOTimeSpentView::changeIncidenceDisplay( Incidence *, int action )
{
switch( action ) {
case KOGlobals::INCIDENCEADDED:
case KOGlobals::INCIDENCEEDITED:
case KOGlobals::INCIDENCEDELETED:
updateView();
break;
default:
break;
}
}
void KOTimeSpentView::updateView()
{
/*
QString text;
text = "<table width=\"100%\">\n";
text += "<tr bgcolor=\"#3679AD\"><td><h1>";
text += "<img src=\"";
// text += todo: put something there.
text += "\">";
text += "<font color=\"white\"> ";
text += i18n("Time tracker") + "</font></h1>";
text += "</td></tr>\n<tr><td>";
text += "<h2>";
if ( mStartDate.daysTo( mEndDate ) < 1 ) {
text += KGlobal::locale()->formatDate( mStartDate );
} else {
text += i18nc("Date from - to", "%1 - %2",
KGlobal::locale()->formatDate( mStartDate ) ,
KGlobal::locale()->formatDate( mEndDate ) );
}
text+="</h2>\n";
*/
KDateTime::Spec timeSpec = KOPrefs::instance()->timeSpec();
mView->mEventList = calendar()->events( mStartDate, mEndDate, timeSpec );
mView->repaint();
}
<|endoftext|>
|
<commit_before>#include <Dusk/Dusk.hpp>
#include <Dusk/Log.hpp>
#include <Dusk/Module.hpp>
#include <Dusk/ScriptConsole.hpp>
#include <Dusk/Graphics/GraphicsDriver.hpp>
#include <Dusk/Graphics/TransformData.hpp>
#include <Dusk/Scene/AxisComponent.hpp>
#include <Dusk/Scene/MeshComponent.hpp>
#include <Dusk/Scene/Entity.hpp>
#include <Dusk/Scene/Scene.hpp>
#include <Dusk/Scene/Camera.hpp>
#include <Dusk/Event.hpp>
#include <thread>
void testFunc(const Dusk::WindowResizedEventData * data)
{
DuskLogInfo("testFunc %s %s",
glm::to_string(data->Delta),
glm::to_string(data->Size));
}
int main(int argc, char** argv)
{
Dusk::SetApplicationName("HelloWorld");
Dusk::SetApplicationVersion({ 1, 0, 0 });
Dusk::Initialize(argc, argv);
if (!Dusk::RunScriptFile("Assets/Scripts/Main.py")) {
DuskLogError("Failed to load Main.py");
return 1;
}
Dusk::ScriptConsole::Initialize();
Dusk::UpdateContext updateContext;
Dusk::RenderContext renderContext;
{
Dusk::Scene scene;
Dusk::Camera camera;
camera.SetPosition({ 10, 10, 10 });
camera.SetLookAt({ 0, 0, 0 });
// scene.AddComponent(std::make_unique<Dusk::AxisComponent>());
auto transformData = renderContext.GetTransformData();
transformData->View = camera.GetView();
transformData->Projection = camera.GetProjection();
// if (!scene.LoadFromFile("Models/cube.obj")) {
// DuskLogError("Failed to load Models/cube.obj");
// }
auto actor = scene.AddChild(std::make_unique<Dusk::Entity>());
auto mesh = std::make_unique<Dusk::MeshComponent>();
mesh->LoadFromFile("Assets/Models/crate/crate.obj");
actor->AddComponent(std::move(mesh));
auto gfx = Dusk::GetGraphicsDriver();
Dusk::WindowResizedEventData testData;
testData.Size = { 1024, 768 };
testData.Delta = { 0, 0 };
gfx->WindowResizedEvent.Call(&testData);
auto shader = gfx->CreateShader();
shader->LoadFromFiles({
"flat.vert",
"flat.frag",
});
Dusk::SetRunning(true);
while (Dusk::IsRunning()) {
gfx->ProcessEvents();
scene.Update(&updateContext);
Dusk::ScriptConsole::Update();
shader->Bind();
scene.Render(&renderContext);
gfx->SwapBuffers();
}
}
Dusk::ScriptConsole::Terminate();
Dusk::Terminate();
return 0;
}
<commit_msg>Fix Delta bugs in HelloWorld<commit_after>#include <Dusk/Dusk.hpp>
#include <Dusk/Log.hpp>
#include <Dusk/Module.hpp>
#include <Dusk/ScriptConsole.hpp>
#include <Dusk/Graphics/GraphicsDriver.hpp>
#include <Dusk/Graphics/TransformData.hpp>
#include <Dusk/Scene/AxisComponent.hpp>
#include <Dusk/Scene/MeshComponent.hpp>
#include <Dusk/Scene/Entity.hpp>
#include <Dusk/Scene/Scene.hpp>
#include <Dusk/Scene/Camera.hpp>
#include <Dusk/Event.hpp>
#include <thread>
void testFunc(const Dusk::WindowResizedEventData * data)
{
DuskLogInfo("testFunc %s",
glm::to_string(data->Size));
}
int main(int argc, char** argv)
{
Dusk::SetApplicationName("HelloWorld");
Dusk::SetApplicationVersion({ 1, 0, 0 });
Dusk::Initialize(argc, argv);
if (!Dusk::RunScriptFile("Assets/Scripts/Main.py")) {
DuskLogError("Failed to load Main.py");
return 1;
}
Dusk::ScriptConsole::Initialize();
Dusk::UpdateContext updateContext;
Dusk::RenderContext renderContext;
{
Dusk::Scene scene;
Dusk::Camera camera;
camera.SetPosition({ 10, 10, 10 });
camera.SetLookAt({ 0, 0, 0 });
// scene.AddComponent(std::make_unique<Dusk::AxisComponent>());
auto transformData = renderContext.GetTransformData();
transformData->View = camera.GetView();
transformData->Projection = camera.GetProjection();
// if (!scene.LoadFromFile("Models/cube.obj")) {
// DuskLogError("Failed to load Models/cube.obj");
// }
auto actor = scene.AddChild(std::make_unique<Dusk::Entity>());
auto mesh = std::make_unique<Dusk::MeshComponent>();
mesh->LoadFromFile("Assets/Models/crate/crate.obj");
actor->AddComponent(std::move(mesh));
auto gfx = Dusk::GetGraphicsDriver();
Dusk::WindowResizedEventData testData;
testData.Size = { 1024, 768 };
gfx->WindowResizedEvent.Call(&testData);
auto shader = gfx->CreateShader();
shader->LoadFromFiles({
"flat.vert",
"flat.frag",
});
Dusk::SetRunning(true);
while (Dusk::IsRunning()) {
gfx->ProcessEvents();
scene.Update(&updateContext);
Dusk::ScriptConsole::Update();
shader->Bind();
scene.Render(&renderContext);
gfx->SwapBuffers();
}
}
Dusk::ScriptConsole::Terminate();
Dusk::Terminate();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2016 Peter Repukat - FlatspotSoftware
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 "SteamTargetRenderer.h"
SteamTargetRenderer::SteamTargetRenderer()
{
getSteamOverlay();
QSettings settings(".\\TargetConfig.ini", QSettings::IniFormat);
settings.beginGroup("BaseConf");
const QStringList childKeys = settings.childKeys();
for (auto &childkey : childKeys)
{
if (childkey == "bDrawDebugEdges")
{
bDrawDebugEdges = settings.value(childkey).toBool();
} else if (childkey == "bEnableOverlay") {
bDrawOverlay = settings.value(childkey).toBool();
} else if (childkey == "bEnableControllers") {
bEnableControllers = settings.value(childkey).toBool();
}else if (childkey == "bHookSteam") {
bHookSteam = settings.value(childkey).toBool();
}
}
settings.endGroup();
#ifndef NDEBUG
bDrawDebugEdges = true;
#endif // NDEBUG
sfCshape = sf::CircleShape(100.f);
sfCshape.setFillColor(sf::Color(128, 128, 128, 128));
sfCshape.setOrigin(sf::Vector2f(100, 100));
sf::VideoMode mode = sf::VideoMode::getDesktopMode();
sfWindow.create(sf::VideoMode(mode.width-16, mode.height-32), "GloSC_OverlayWindow"); //Window is too large ; always 16 and 32 pixels? - sf::Style::None breaks transparency!
sfWindow.setVerticalSyncEnabled(bVsync);
if (!bVsync)
sfWindow.setFramerateLimit(iRefreshRate);
sfWindow.setPosition(sf::Vector2i(0, 0));
makeSfWindowTransparent(sfWindow);
sfWindow.setActive(false);
consoleHwnd = GetConsoleWindow(); //We need a console for a dirty hack to make sure we stay in game bindings - Also useful for debugging
if (bEnableControllers)
controllerThread.run();
QTimer::singleShot(2000, this, &SteamTargetRenderer::launchApp); // lets steam do its thing
}
SteamTargetRenderer::~SteamTargetRenderer()
{
bRunLoop = false;
renderThread.join();
if (controllerThread.isRunning())
controllerThread.stop();
}
void SteamTargetRenderer::run()
{
renderThread = std::thread(&SteamTargetRenderer::RunSfWindowLoop, this);
}
void SteamTargetRenderer::RunSfWindowLoop()
{
if (!bRunLoop)
return;
sfWindow.setActive(true);
sf::Clock reCheckControllerTimer;
bool focusSwitchNeeded = true;
if (!bDrawOverlay)
{
ShowWindow(consoleHwnd, SW_HIDE);
}
if (bDrawOverlay)
{
SetWindowPos(sfWindow.getSystemHandle(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS);
} else {
ShowWindow(consoleHwnd, SW_HIDE);
}
while (sfWindow.isOpen() && bRunLoop)
{
sf::Event event;
while (sfWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
sfWindow.close();
}
sfWindow.clear(sf::Color::Transparent);
if (bDrawDebugEdges)
drawDebugEdges();
sfWindow.display();
//This ensures that we stay in game binding, even if focused application changes! (Why does this work? Well, i dunno... ask Valve...)
//Only works with a console window
//Causes trouble as soon as there is more than the consoleWindow and the overlayWindow
//This is trying to avoid hooking Steam.exe
//----
//alternatively, we can just hook steam and make our lives so much easier
//we inject and hook here to spare IPC and let the dll grab the steam appID of the launched process when the config switches (config switches w/ focus)
if (focusSwitchNeeded)
{
if (bHookSteam)
hookBindings(); //cleanup - unhooking / unloading of dll is managed by the GloSC gamelauncher rather than here
focusSwitchNeeded = false;
SetFocus(consoleHwnd);
sf::Clock clock;
while (!SetForegroundWindow(consoleHwnd) && clock.getElapsedTime().asMilliseconds() < 1000) //try to forcefully set foreground window
{
Sleep(1);
}
}
//Dirty hack to make the steamoverlay work properly and still keep Apps Controllerconfig when closing overlay.
//even if hooking steam, this ensures the overlay stays working
if (overlayPtr != NULL)
{
char overlayOpen = *(char*)overlayPtr;
if (overlayOpen)
{
if (!bNeedFocusSwitch)
{
bNeedFocusSwitch = true;
hwForeGroundWindow = GetForegroundWindow();
std::cout << "Saving current ForegorundWindow HWND: " << hwForeGroundWindow << std::endl;
std::cout << "Activating OverlayWindow" << std::endl;
SetWindowLong(sfWindow.getSystemHandle(), GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TOOLWINDOW); //make overlay window clickable
//Actually activate the overlaywindow
SetFocus(sfWindow.getSystemHandle());
//Move the mouse cursor inside the overlaywindow
//this is neccessary because steam doesn't want to switch to big picture bindings if mouse isn't inside
SetCursorPos(16, 16);
//by activating the consolewindow **and bringing it to the foreground** we can trick steam so the controller stays in game bindings
SetFocus(consoleHwnd);
sf::Clock clock;
while (!SetForegroundWindow(consoleHwnd) && clock.getElapsedTime().asMilliseconds() < 1000) //try to forcefully set foreground window
{
Sleep(1);
}
}
} else {
if (bNeedFocusSwitch)
{
std::cout << "Deactivating OverlayWindow" << std::endl;
//make overlaywindow clickthrough - WS_EX_TRANSPARENT - again
SetWindowLong(sfWindow.getSystemHandle(), GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW);
std::cout << "Switching to previously focused window" << std::endl;
//switch back the the previosly focused window
SetFocus(hwForeGroundWindow);
sf::Clock clock;
while (!SetForegroundWindow(hwForeGroundWindow) && clock.getElapsedTime().asMilliseconds() < 1000) //try to forcefully set foreground window
{
Sleep(1);
}
bNeedFocusSwitch = false;
}
}
}
}
}
void SteamTargetRenderer::getSteamOverlay()
{
#ifdef _AMD64_
hmodGameOverlayRenderer = GetModuleHandle(L"Gameoverlayrenderer64.dll");
if (hmodGameOverlayRenderer != NULL)
{
std::cout << "GameOverlayrenderer64.dll found; Module at: 0x" << hmodGameOverlayRenderer << std::endl;
overlayPtr = (uint64_t*)(uint64_t(hmodGameOverlayRenderer) + 0x1365e8);
overlayPtr = (uint64_t*)(*overlayPtr + 0x40);
}
#else
hmodGameOverlayRenderer = GetModuleHandle(L"Gameoverlayrenderer.dll");
if (hmodGameOverlayRenderer != NULL)
{
std::cout << "GameOverlayrenderer.dll found; Module at: 0x" << hmodGameOverlayRenderer << std::endl;
overlayPtr = (uint32_t*)(uint32_t(hmodGameOverlayRenderer) + 0xED7A0);
//overlayPtr = (uint32_t*)(*overlayPtr + 0x40);
}
#endif
}
void SteamTargetRenderer::makeSfWindowTransparent(sf::RenderWindow & window)
{
HWND hwnd = window.getSystemHandle();
SetWindowLong(hwnd, GWL_STYLE, WS_VISIBLE | WS_POPUP &~WS_CAPTION);
SetWindowLong(hwnd, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_TOOLWINDOW);
MARGINS margins;
margins.cxLeftWidth = -1;
DwmExtendFrameIntoClientArea(hwnd, &margins);
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
window.clear(sf::Color::Transparent);
window.display();
}
void SteamTargetRenderer::drawDebugEdges()
{
sfCshape.setPosition(sf::Vector2f(-25, -25));
sfWindow.draw(sfCshape);
sfCshape.setPosition(sf::Vector2f(sfWindow.getSize().x + 25, -25));
sfWindow.draw(sfCshape);
sfCshape.setPosition(sf::Vector2f(-25, sfWindow.getSize().y));
sfWindow.draw(sfCshape);
sfCshape.setPosition(sf::Vector2f(sfWindow.getSize().x, sfWindow.getSize().y));
sfWindow.draw(sfCshape);
}
void SteamTargetRenderer::hookBindings()
{
std::cout << "Hooking Steam..." << std::endl;
QString dir = QDir::toNativeSeparators(QCoreApplication::applicationDirPath());
dir = dir.mid(0, dir.lastIndexOf("\\"));
QProcess proc;
proc.setNativeArguments(" --inject ");
proc.setWorkingDirectory(dir);
proc.start("..\\Injector.exe", QIODevice::ReadOnly);
proc.waitForStarted();
proc.waitForFinished();
if (QString::fromStdString(proc.readAll().toStdString()).contains("Inject success!")) //if we have injected (and patched the function)
{
std::cout << "Successfully hooked Steam!" << std::endl;
//tell the GloSC_GameLauncher that we have hooked steam
//it will deal with checking if the target is still alive and unload the dll / unhook then
// - ensures unloading / unhooking even if this process crashes or gets unexpectedly killed
QSharedMemory sharedMemInstance("GloSC_GameLauncher");
if (!sharedMemInstance.create(1024) && sharedMemInstance.error() == QSharedMemory::AlreadyExists)
{
QBuffer buffer;
QDataStream dataStream(&buffer);
QStringList stringList;
sharedMemInstance.attach();
sharedMemInstance.lock();
buffer.setData((char*)sharedMemInstance.constData(), sharedMemInstance.size());
buffer.open(QBuffer::ReadOnly);
dataStream >> stringList;
buffer.close();
int i = stringList.indexOf(IsSteamHooked) + 1;
stringList.replace(i, "1");
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << stringList;
int size = buffer.size();
char *to = (char*)sharedMemInstance.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemInstance.size(), size));
buffer.close();
sharedMemInstance.unlock();
sharedMemInstance.detach();
}
} else {
std::cout << "Hooking Steam failed!" << std::endl;
}
}
void SteamTargetRenderer::launchApp()
{
bool launchGame = false;
bool closeWhenDone = false;
QString type = "Win32";
QString path = "";
QSettings settings(".\\TargetConfig.ini", QSettings::IniFormat);
settings.beginGroup("LaunchGame");
const QStringList childKeys = settings.childKeys();
for (auto &childkey : childKeys)
{
if (childkey == "bLaunchGame")
{
launchGame = settings.value(childkey).toBool();
}
else if (childkey == "Type") {
type = settings.value(childkey).toString();
}
else if (childkey == "Path") {
path = settings.value(childkey).toString();
}
else if (childkey == "bCloseWhenDone") {
closeWhenDone = settings.value("bCloseWhenDone").toBool();
}
}
settings.endGroup();
if (launchGame)
{
QSharedMemory sharedMemInstance("GloSC_GameLauncher");
if (!sharedMemInstance.create(1024) && sharedMemInstance.error() == QSharedMemory::AlreadyExists)
{
QBuffer buffer;
QDataStream dataStream(&buffer);
QStringList stringList;
sharedMemInstance.attach();
sharedMemInstance.lock();
buffer.setData((char*)sharedMemInstance.constData(), sharedMemInstance.size());
buffer.open(QBuffer::ReadOnly);
dataStream >> stringList;
buffer.close();
int lgt_index = stringList.indexOf(LaunchGame);
stringList.replace(lgt_index + 1, type);
stringList.replace(lgt_index + 2, path);
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << stringList;
int size = buffer.size();
char *to = (char*)sharedMemInstance.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemInstance.size(), size));
buffer.close();
sharedMemInstance.unlock();
sharedMemInstance.detach();
if (closeWhenDone)
{
updateTimer.setInterval(1111);
connect(&updateTimer, SIGNAL(timeout()), this, SLOT(checkSharedMem()));
updateTimer.start();
}
}
}
}
void SteamTargetRenderer::checkSharedMem()
{
QSharedMemory sharedMemInstance("GloSC_GameLauncher");
if (!sharedMemInstance.create(1024) && sharedMemInstance.error() == QSharedMemory::AlreadyExists)
{
QBuffer buffer;
QDataStream in(&buffer);
QStringList stringList;
sharedMemInstance.attach();
sharedMemInstance.lock();
buffer.setData((char*)sharedMemInstance.constData(), sharedMemInstance.size());
buffer.open(QBuffer::ReadOnly);
in >> stringList;
buffer.close();
sharedMemInstance.unlock();
sharedMemInstance.detach();
int close_index = stringList.indexOf(LaunchedProcessFinished)+1;
if (close_index > 0 && stringList.at(close_index).toInt() == 1)
{
bRunLoop = false;
renderThread.join();
if (controllerThread.isRunning())
controllerThread.stop();
exit(0);
}
}
}
<commit_msg>SteamTarget: Force 60FPS lock<commit_after>/*
Copyright 2016 Peter Repukat - FlatspotSoftware
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 "SteamTargetRenderer.h"
SteamTargetRenderer::SteamTargetRenderer()
{
getSteamOverlay();
QSettings settings(".\\TargetConfig.ini", QSettings::IniFormat);
settings.beginGroup("BaseConf");
const QStringList childKeys = settings.childKeys();
for (auto &childkey : childKeys)
{
if (childkey == "bDrawDebugEdges")
{
bDrawDebugEdges = settings.value(childkey).toBool();
} else if (childkey == "bEnableOverlay") {
bDrawOverlay = settings.value(childkey).toBool();
} else if (childkey == "bEnableControllers") {
bEnableControllers = settings.value(childkey).toBool();
}else if (childkey == "bHookSteam") {
bHookSteam = settings.value(childkey).toBool();
}
}
settings.endGroup();
#ifndef NDEBUG
bDrawDebugEdges = true;
#endif // NDEBUG
sfCshape = sf::CircleShape(100.f);
sfCshape.setFillColor(sf::Color(128, 128, 128, 128));
sfCshape.setOrigin(sf::Vector2f(100, 100));
sf::VideoMode mode = sf::VideoMode::getDesktopMode();
sfWindow.create(sf::VideoMode(mode.width-16, mode.height-32), "GloSC_OverlayWindow"); //Window is too large ; always 16 and 32 pixels? - sf::Style::None breaks transparency!
sfWindow.setVerticalSyncEnabled(bVsync);
sfWindow.setFramerateLimit(iRefreshRate);
sfWindow.setPosition(sf::Vector2i(0, 0));
makeSfWindowTransparent(sfWindow);
sfWindow.setActive(false);
consoleHwnd = GetConsoleWindow(); //We need a console for a dirty hack to make sure we stay in game bindings - Also useful for debugging
if (bEnableControllers)
controllerThread.run();
QTimer::singleShot(2000, this, &SteamTargetRenderer::launchApp); // lets steam do its thing
}
SteamTargetRenderer::~SteamTargetRenderer()
{
bRunLoop = false;
renderThread.join();
if (controllerThread.isRunning())
controllerThread.stop();
}
void SteamTargetRenderer::run()
{
renderThread = std::thread(&SteamTargetRenderer::RunSfWindowLoop, this);
}
void SteamTargetRenderer::RunSfWindowLoop()
{
if (!bRunLoop)
return;
sfWindow.setActive(true);
sf::Clock reCheckControllerTimer;
bool focusSwitchNeeded = true;
if (!bDrawOverlay)
{
ShowWindow(consoleHwnd, SW_HIDE);
}
if (bDrawOverlay)
{
SetWindowPos(sfWindow.getSystemHandle(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS);
} else {
ShowWindow(consoleHwnd, SW_HIDE);
}
while (sfWindow.isOpen() && bRunLoop)
{
sf::Event event;
while (sfWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
sfWindow.close();
}
sfWindow.clear(sf::Color::Transparent);
if (bDrawDebugEdges)
drawDebugEdges();
sfWindow.display();
//This ensures that we stay in game binding, even if focused application changes! (Why does this work? Well, i dunno... ask Valve...)
//Only works with a console window
//Causes trouble as soon as there is more than the consoleWindow and the overlayWindow
//This is trying to avoid hooking Steam.exe
//----
//alternatively, we can just hook steam and make our lives so much easier
//we inject and hook here to spare IPC and let the dll grab the steam appID of the launched process when the config switches (config switches w/ focus)
if (focusSwitchNeeded)
{
if (bHookSteam)
hookBindings(); //cleanup - unhooking / unloading of dll is managed by the GloSC gamelauncher rather than here
focusSwitchNeeded = false;
SetFocus(consoleHwnd);
sf::Clock clock;
while (!SetForegroundWindow(consoleHwnd) && clock.getElapsedTime().asMilliseconds() < 1000) //try to forcefully set foreground window
{
Sleep(1);
}
}
//Dirty hack to make the steamoverlay work properly and still keep Apps Controllerconfig when closing overlay.
//even if hooking steam, this ensures the overlay stays working
if (overlayPtr != NULL)
{
char overlayOpen = *(char*)overlayPtr;
if (overlayOpen)
{
if (!bNeedFocusSwitch)
{
bNeedFocusSwitch = true;
hwForeGroundWindow = GetForegroundWindow();
std::cout << "Saving current ForegorundWindow HWND: " << hwForeGroundWindow << std::endl;
std::cout << "Activating OverlayWindow" << std::endl;
SetWindowLong(sfWindow.getSystemHandle(), GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TOOLWINDOW); //make overlay window clickable
//Actually activate the overlaywindow
SetFocus(sfWindow.getSystemHandle());
//Move the mouse cursor inside the overlaywindow
//this is neccessary because steam doesn't want to switch to big picture bindings if mouse isn't inside
SetCursorPos(16, 16);
//by activating the consolewindow **and bringing it to the foreground** we can trick steam so the controller stays in game bindings
SetFocus(consoleHwnd);
sf::Clock clock;
while (!SetForegroundWindow(consoleHwnd) && clock.getElapsedTime().asMilliseconds() < 1000) //try to forcefully set foreground window
{
Sleep(1);
}
}
} else {
if (bNeedFocusSwitch)
{
std::cout << "Deactivating OverlayWindow" << std::endl;
//make overlaywindow clickthrough - WS_EX_TRANSPARENT - again
SetWindowLong(sfWindow.getSystemHandle(), GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW);
std::cout << "Switching to previously focused window" << std::endl;
//switch back the the previosly focused window
SetFocus(hwForeGroundWindow);
sf::Clock clock;
while (!SetForegroundWindow(hwForeGroundWindow) && clock.getElapsedTime().asMilliseconds() < 1000) //try to forcefully set foreground window
{
Sleep(1);
}
bNeedFocusSwitch = false;
}
}
}
}
}
void SteamTargetRenderer::getSteamOverlay()
{
#ifdef _AMD64_
hmodGameOverlayRenderer = GetModuleHandle(L"Gameoverlayrenderer64.dll");
if (hmodGameOverlayRenderer != NULL)
{
std::cout << "GameOverlayrenderer64.dll found; Module at: 0x" << hmodGameOverlayRenderer << std::endl;
overlayPtr = (uint64_t*)(uint64_t(hmodGameOverlayRenderer) + 0x1365e8);
overlayPtr = (uint64_t*)(*overlayPtr + 0x40);
}
#else
hmodGameOverlayRenderer = GetModuleHandle(L"Gameoverlayrenderer.dll");
if (hmodGameOverlayRenderer != NULL)
{
std::cout << "GameOverlayrenderer.dll found; Module at: 0x" << hmodGameOverlayRenderer << std::endl;
overlayPtr = (uint32_t*)(uint32_t(hmodGameOverlayRenderer) + 0xED7A0);
//overlayPtr = (uint32_t*)(*overlayPtr + 0x40);
}
#endif
}
void SteamTargetRenderer::makeSfWindowTransparent(sf::RenderWindow & window)
{
HWND hwnd = window.getSystemHandle();
SetWindowLong(hwnd, GWL_STYLE, WS_VISIBLE | WS_POPUP &~WS_CAPTION);
SetWindowLong(hwnd, GWL_EXSTYLE, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_TOOLWINDOW);
MARGINS margins;
margins.cxLeftWidth = -1;
DwmExtendFrameIntoClientArea(hwnd, &margins);
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE);
window.clear(sf::Color::Transparent);
window.display();
}
void SteamTargetRenderer::drawDebugEdges()
{
sfCshape.setPosition(sf::Vector2f(-25, -25));
sfWindow.draw(sfCshape);
sfCshape.setPosition(sf::Vector2f(sfWindow.getSize().x + 25, -25));
sfWindow.draw(sfCshape);
sfCshape.setPosition(sf::Vector2f(-25, sfWindow.getSize().y));
sfWindow.draw(sfCshape);
sfCshape.setPosition(sf::Vector2f(sfWindow.getSize().x, sfWindow.getSize().y));
sfWindow.draw(sfCshape);
}
void SteamTargetRenderer::hookBindings()
{
std::cout << "Hooking Steam..." << std::endl;
QString dir = QDir::toNativeSeparators(QCoreApplication::applicationDirPath());
dir = dir.mid(0, dir.lastIndexOf("\\"));
QProcess proc;
proc.setNativeArguments(" --inject ");
proc.setWorkingDirectory(dir);
proc.start("..\\Injector.exe", QIODevice::ReadOnly);
proc.waitForStarted();
proc.waitForFinished();
if (QString::fromStdString(proc.readAll().toStdString()).contains("Inject success!")) //if we have injected (and patched the function)
{
std::cout << "Successfully hooked Steam!" << std::endl;
//tell the GloSC_GameLauncher that we have hooked steam
//it will deal with checking if the target is still alive and unload the dll / unhook then
// - ensures unloading / unhooking even if this process crashes or gets unexpectedly killed
QSharedMemory sharedMemInstance("GloSC_GameLauncher");
if (!sharedMemInstance.create(1024) && sharedMemInstance.error() == QSharedMemory::AlreadyExists)
{
QBuffer buffer;
QDataStream dataStream(&buffer);
QStringList stringList;
sharedMemInstance.attach();
sharedMemInstance.lock();
buffer.setData((char*)sharedMemInstance.constData(), sharedMemInstance.size());
buffer.open(QBuffer::ReadOnly);
dataStream >> stringList;
buffer.close();
int i = stringList.indexOf(IsSteamHooked) + 1;
stringList.replace(i, "1");
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << stringList;
int size = buffer.size();
char *to = (char*)sharedMemInstance.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemInstance.size(), size));
buffer.close();
sharedMemInstance.unlock();
sharedMemInstance.detach();
}
} else {
std::cout << "Hooking Steam failed!" << std::endl;
}
}
void SteamTargetRenderer::launchApp()
{
bool launchGame = false;
bool closeWhenDone = false;
QString type = "Win32";
QString path = "";
QSettings settings(".\\TargetConfig.ini", QSettings::IniFormat);
settings.beginGroup("LaunchGame");
const QStringList childKeys = settings.childKeys();
for (auto &childkey : childKeys)
{
if (childkey == "bLaunchGame")
{
launchGame = settings.value(childkey).toBool();
}
else if (childkey == "Type") {
type = settings.value(childkey).toString();
}
else if (childkey == "Path") {
path = settings.value(childkey).toString();
}
else if (childkey == "bCloseWhenDone") {
closeWhenDone = settings.value("bCloseWhenDone").toBool();
}
}
settings.endGroup();
if (launchGame)
{
QSharedMemory sharedMemInstance("GloSC_GameLauncher");
if (!sharedMemInstance.create(1024) && sharedMemInstance.error() == QSharedMemory::AlreadyExists)
{
QBuffer buffer;
QDataStream dataStream(&buffer);
QStringList stringList;
sharedMemInstance.attach();
sharedMemInstance.lock();
buffer.setData((char*)sharedMemInstance.constData(), sharedMemInstance.size());
buffer.open(QBuffer::ReadOnly);
dataStream >> stringList;
buffer.close();
int lgt_index = stringList.indexOf(LaunchGame);
stringList.replace(lgt_index + 1, type);
stringList.replace(lgt_index + 2, path);
buffer.open(QBuffer::ReadWrite);
QDataStream out(&buffer);
out << stringList;
int size = buffer.size();
char *to = (char*)sharedMemInstance.data();
const char *from = buffer.data().data();
memcpy(to, from, qMin(sharedMemInstance.size(), size));
buffer.close();
sharedMemInstance.unlock();
sharedMemInstance.detach();
if (closeWhenDone)
{
updateTimer.setInterval(1111);
connect(&updateTimer, SIGNAL(timeout()), this, SLOT(checkSharedMem()));
updateTimer.start();
}
}
}
}
void SteamTargetRenderer::checkSharedMem()
{
QSharedMemory sharedMemInstance("GloSC_GameLauncher");
if (!sharedMemInstance.create(1024) && sharedMemInstance.error() == QSharedMemory::AlreadyExists)
{
QBuffer buffer;
QDataStream in(&buffer);
QStringList stringList;
sharedMemInstance.attach();
sharedMemInstance.lock();
buffer.setData((char*)sharedMemInstance.constData(), sharedMemInstance.size());
buffer.open(QBuffer::ReadOnly);
in >> stringList;
buffer.close();
sharedMemInstance.unlock();
sharedMemInstance.detach();
int close_index = stringList.indexOf(LaunchedProcessFinished)+1;
if (close_index > 0 && stringList.at(close_index).toInt() == 1)
{
bRunLoop = false;
renderThread.join();
if (controllerThread.isRunning())
controllerThread.stop();
exit(0);
}
}
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
// author: Baozeng Ding <[email protected]>
//------------------------------------------------------------------------------
#include "NullDerefProtectionTransformer.h"
#include "cling/Interpreter/Transaction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Mangle.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/InstIterator.h"
namespace cling {
NullDerefProtectionTransformer::NullDerefProtectionTransformer()
: FailBB(0), TransactionTransformer(/*Sema=*/0) {}
NullDerefProtectionTransformer::~NullDerefProtectionTransformer()
{}
void NullDerefProtectionTransformer::Transform() {
using namespace clang;
FunctionDecl* FD = getTransaction()->getWrapperFD();
if (!FD)
return;
// Copied from Interpreter.cpp;
if (!m_MangleCtx)
m_MangleCtx.reset(FD->getASTContext().createMangleContext());
std::string mangledName;
if (m_MangleCtx->shouldMangleDeclName(FD)) {
llvm::raw_string_ostream RawStr(mangledName);
switch(FD->getKind()) {
case Decl::CXXConstructor:
//Ctor_Complete, // Complete object ctor
//Ctor_Base, // Base object ctor
//Ctor_CompleteAllocating // Complete object allocating ctor (unused)
m_MangleCtx->mangleCXXCtor(cast<CXXConstructorDecl>(FD),
Ctor_Complete, RawStr);
break;
case Decl::CXXDestructor:
//Dtor_Deleting, // Deleting dtor
//Dtor_Complete, // Complete object dtor
//Dtor_Base // Base object dtor
m_MangleCtx->mangleCXXDtor(cast<CXXDestructorDecl>(FD),
Dtor_Deleting, RawStr);
break;
default :
m_MangleCtx->mangleName(FD, RawStr);
break;
}
RawStr.flush();
} else {
mangledName = FD->getNameAsString();
}
// Find the function in the module.
llvm::Function* F
= getTransaction()->getModule()->getFunction(mangledName);
if (F)
runOnFunction(*F);
}
llvm::BasicBlock* NullDerefProtectionTransformer::getTrapBB() {
if (FailBB) return FailBB;
llvm::Function *Fn = Inst->getParent()->getParent();
llvm::LLVMContext& ctx = Fn->getContext();
FailBB = llvm::BasicBlock::Create(ctx, "FailBlock", Fn);
llvm::ReturnInst::Create(Fn->getContext(), FailBB);
return FailBB;
}
void NullDerefProtectionTransformer::instrumentLoadInst(llvm::LoadInst *LI) {
LI->dump();
llvm::Value * Addr = LI->getOperand(0);
Addr->dump();
LI->getParent()->getParent()->dump();
llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
llvm::Type * ElTy = PTy -> getElementType();
if (!ElTy->isPointerTy()) {
llvm::BasicBlock *OldBB = LI->getParent();
llvm::ICmpInst *Cmp
= new llvm::ICmpInst(LI, llvm::CmpInst::ICMP_EQ, Addr,
llvm::Constant::getNullValue(Addr->getType()), "");
llvm::Instruction *Inst = Builder->GetInsertPoint();
llvm::BasicBlock *NewBB = OldBB->splitBasicBlock(Inst);
OldBB->getTerminator()->eraseFromParent();
llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
}
}
void NullDerefProtectionTransformer::instrumentStoreInst(llvm::StoreInst *SI){
llvm::Value * Addr = SI->getOperand(1);
llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
llvm::Type * ElTy = PTy -> getElementType();
if (!ElTy->isPointerTy()) {
llvm::BasicBlock *OldBB = SI->getParent();
llvm::ICmpInst *Cmp
= new llvm::ICmpInst(SI, llvm::CmpInst::ICMP_EQ, Addr,
llvm::Constant::getNullValue(Addr->getType()), "");
llvm::Instruction *Inst = Builder->GetInsertPoint();
llvm::BasicBlock *NewBB = OldBB->splitBasicBlock(Inst);
OldBB->getTerminator()->eraseFromParent();
llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
}
}
bool NullDerefProtectionTransformer::runOnFunction(llvm::Function &F) {
llvm::IRBuilder<> TheBuilder(F.getContext());
Builder = &TheBuilder;
std::vector<llvm::Instruction*> WorkList;
for (llvm::inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
llvm::Instruction *I = &*i;
if (llvm::isa<llvm::LoadInst>(I) || llvm::isa<llvm::StoreInst>(I))
WorkList.push_back(I);
}
for (std::vector<llvm::Instruction*>::iterator i = WorkList.begin(),
e = WorkList.end(); i != e; ++i) {
Inst = *i;
Builder->SetInsertPoint(Inst);
if (llvm::LoadInst *LI = llvm::dyn_cast<llvm::LoadInst>(Inst)) {
instrumentLoadInst(LI);
LI->dump();
} else if (llvm::StoreInst *SI = llvm::dyn_cast<llvm::StoreInst>(Inst)) {
instrumentStoreInst(SI);
SI->dump();
} else {
llvm_unreachable("unknown Instruction type");
}
}
return true;
}
} // end namespace cling
<commit_msg>It wasn't Baozeng's fault I committed the old instead of the newest patch.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
// author: Baozeng Ding <[email protected]>
//------------------------------------------------------------------------------
#include "NullDerefProtectionTransformer.h"
#include "cling/Interpreter/Transaction.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Mangle.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/InstIterator.h"
namespace cling {
NullDerefProtectionTransformer::NullDerefProtectionTransformer()
: FailBB(0), TransactionTransformer(/*Sema=*/0) {}
NullDerefProtectionTransformer::~NullDerefProtectionTransformer()
{}
void NullDerefProtectionTransformer::Transform() {
using namespace clang;
FunctionDecl* FD = getTransaction()->getWrapperFD();
if (!FD)
return;
// Copied from Interpreter.cpp;
if (!m_MangleCtx)
m_MangleCtx.reset(FD->getASTContext().createMangleContext());
std::string mangledName;
if (m_MangleCtx->shouldMangleDeclName(FD)) {
llvm::raw_string_ostream RawStr(mangledName);
switch(FD->getKind()) {
case Decl::CXXConstructor:
//Ctor_Complete, // Complete object ctor
//Ctor_Base, // Base object ctor
//Ctor_CompleteAllocating // Complete object allocating ctor (unused)
m_MangleCtx->mangleCXXCtor(cast<CXXConstructorDecl>(FD),
Ctor_Complete, RawStr);
break;
case Decl::CXXDestructor:
//Dtor_Deleting, // Deleting dtor
//Dtor_Complete, // Complete object dtor
//Dtor_Base // Base object dtor
m_MangleCtx->mangleCXXDtor(cast<CXXDestructorDecl>(FD),
Dtor_Deleting, RawStr);
break;
default :
m_MangleCtx->mangleName(FD, RawStr);
break;
}
RawStr.flush();
} else {
mangledName = FD->getNameAsString();
}
// Find the function in the module.
llvm::Function* F
= getTransaction()->getModule()->getFunction(mangledName);
if (F)
runOnFunction(*F);
}
llvm::BasicBlock* NullDerefProtectionTransformer::getTrapBB() {
llvm::Function *Fn = Inst->getParent()->getParent();
llvm::LLVMContext& ctx = Fn->getContext();
FailBB = llvm::BasicBlock::Create(ctx, "FailBlock", Fn);
llvm::ReturnInst::Create(Fn->getContext(), FailBB);
return FailBB;
}
void NullDerefProtectionTransformer::instrumentLoadInst(llvm::LoadInst *LI) {
llvm::Value * Addr = LI->getOperand(0);
llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
llvm::Type * ElTy = PTy -> getElementType();
if (!ElTy->isPointerTy()) {
llvm::BasicBlock *OldBB = LI->getParent();
llvm::ICmpInst *Cmp
= new llvm::ICmpInst(LI, llvm::CmpInst::ICMP_EQ, Addr,
llvm::Constant::getNullValue(Addr->getType()), "");
llvm::Instruction *Inst = Builder->GetInsertPoint();
llvm::BasicBlock *NewBB = OldBB->splitBasicBlock(Inst);
OldBB->getTerminator()->eraseFromParent();
llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
}
}
void NullDerefProtectionTransformer::instrumentStoreInst(llvm::StoreInst *SI){
llvm::Value * Addr = SI->getOperand(1);
llvm::PointerType* PTy = llvm::cast<llvm::PointerType>(Addr->getType());
llvm::Type * ElTy = PTy -> getElementType();
if (!ElTy->isPointerTy()) {
llvm::BasicBlock *OldBB = SI->getParent();
llvm::ICmpInst *Cmp
= new llvm::ICmpInst(SI, llvm::CmpInst::ICMP_EQ, Addr,
llvm::Constant::getNullValue(Addr->getType()), "");
llvm::Instruction *Inst = Builder->GetInsertPoint();
llvm::BasicBlock *NewBB = OldBB->splitBasicBlock(Inst);
OldBB->getTerminator()->eraseFromParent();
llvm::BranchInst::Create(getTrapBB(), NewBB, Cmp, OldBB);
}
}
bool NullDerefProtectionTransformer::runOnFunction(llvm::Function &F) {
llvm::IRBuilder<> TheBuilder(F.getContext());
Builder = &TheBuilder;
std::vector<llvm::Instruction*> WorkList;
for (llvm::inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) {
llvm::Instruction *I = &*i;
if (llvm::isa<llvm::LoadInst>(I) || llvm::isa<llvm::StoreInst>(I))
WorkList.push_back(I);
}
for (std::vector<llvm::Instruction*>::iterator i = WorkList.begin(),
e = WorkList.end(); i != e; ++i) {
Inst = *i;
Builder->SetInsertPoint(Inst);
if (llvm::LoadInst *LI = llvm::dyn_cast<llvm::LoadInst>(Inst)) {
instrumentLoadInst(LI);
} else if (llvm::StoreInst *SI = llvm::dyn_cast<llvm::StoreInst>(Inst)) {
instrumentStoreInst(SI);
} else {
llvm_unreachable("unknown Instruction type");
}
}
return true;
}
} // end namespace cling
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "ChainedConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs
/// Returns NULL on error.
static const clang::driver::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
//______________________________________
DiagnosticOptions DefaultDiagnosticOptions;
DefaultDiagnosticOptions.ShowColors = 1;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DiagnosticPrinter, /*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
bool IsProduction = false;
assert(IsProduction = true && "set IsProduction if asserts are on.");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
IsProduction,
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation; // LEAKS!
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
// Update ResourceDir
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::sys::Path oldResInc(Opts.ResourceDir);
oldResInc.appendComponent("include");
llvm::sys::Path newResInc(resource_path);
newResInc.appendComponent("include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsUserSupplied && !E.IsFramework
&& E.Group == clang::frontend::System && E.IgnoreSysRoot
&& E.IsInternal && !E.ImplicitExternC
&& oldResInc.str() == E.Path) {
E.Path = newResInc.str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
// Set up the ASTConsumers
CI->setASTConsumer(new ChainedConsumer());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Prefix, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
Opts.ObjCNonFragileABI2 = 0;
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
// We need C++11 for lookupClass() to find enums.
Opts.CPlusPlus0x = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
if (Target.getTriple().getArch() == llvm::Triple::x86) {
Opts.ObjCNonFragileABI = 1;
} else {
Opts.ObjCNonFragileABI = 0;
}
if (Target.getTriple().isOSDarwin()) {
Opts.NeXTRuntime = 1;
} else {
Opts.NeXTRuntime = 0;
}
}
} // end namespace
<commit_msg>Unfortunately c++11 is more incompatible than I thought, revert this.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "ChainedConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Job.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
/// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs
/// Returns NULL on error.
static const clang::driver::ArgStringList
*GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,
clang::driver::Compilation *Compilation) {
// We expect to get back exactly one Command job, if we didn't something
// failed. Extract that job from the Compilation.
const clang::driver::JobList &Jobs = Compilation->getJobs();
if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {
// diagnose this...
return NULL;
}
// The one job we find should be to invoke clang again.
const clang::driver::Command *Cmd
= cast<clang::driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
// diagnose this...
return NULL;
}
return &Cmd->getArguments();
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,
llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
int argc,
const char* const *argv,
const char* llvmdir) {
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path
= CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
//______________________________________
DiagnosticOptions DefaultDiagnosticOptions;
DefaultDiagnosticOptions.ShowColors = 1;
TextDiagnosticPrinter* DiagnosticPrinter
= new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());
DiagnosticsEngine* Diagnostics
= new DiagnosticsEngine(DiagIDs, DiagnosticPrinter, /*Owns it*/ true); // LEAKS!
std::vector<const char*> argvCompile(argv, argv + argc);
// We do C++ by default; append right after argv[0] name
// Only insert it if there is no other "-x":
bool haveMinusX = false;
for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;
++iarg) {
haveMinusX = !strcmp(*iarg, "-x");
}
if (!haveMinusX) {
argvCompile.insert(argvCompile.begin() + 1,"-x");
argvCompile.insert(argvCompile.begin() + 2, "c++");
}
argvCompile.push_back("-c");
argvCompile.push_back("-");
bool IsProduction = false;
assert(IsProduction = true && "set IsProduction if asserts are on.");
clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),
"cling.out",
IsProduction,
*Diagnostics);
//Driver.setWarnMissingInput(false);
Driver.setCheckInputsExist(false); // think foo.C(12)
llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());
llvm::OwningPtr<clang::driver::Compilation>
Compilation(Driver.BuildCompilation(RF));
const clang::driver::ArgStringList* CC1Args
= GetCC1Arguments(Diagnostics, Compilation.get());
if (CC1Args == NULL) {
return 0;
}
clang::CompilerInvocation*
Invocation = new clang::CompilerInvocation; // LEAKS!
clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,
CC1Args->data() + CC1Args->size(),
*Diagnostics);
Invocation->getFrontendOpts().DisableFree = true;
// Update ResourceDir
if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&
!resource_path.empty()) {
// header search opts' entry for resource_path/include isn't
// updated by providing a new resource path; update it manually.
clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();
llvm::sys::Path oldResInc(Opts.ResourceDir);
oldResInc.appendComponent("include");
llvm::sys::Path newResInc(resource_path);
newResInc.appendComponent("include");
bool foundOldResInc = false;
for (unsigned i = 0, e = Opts.UserEntries.size();
!foundOldResInc && i != e; ++i) {
HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
if (!E.IsUserSupplied && !E.IsFramework
&& E.Group == clang::frontend::System && E.IgnoreSysRoot
&& E.IsInternal && !E.ImplicitExternC
&& oldResInc.str() == E.Path) {
E.Path = newResInc.str();
foundOldResInc = true;
}
}
Opts.ResourceDir = resource_path.str();
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
CI->setInvocation(Invocation);
CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
Invocation->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOpts());
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(),
PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(),
/*size_reserve*/0, /*DelayInit*/false);
CI->setASTContext(Ctx);
// Set up the ASTConsumers
CI->setASTConsumer(new ChainedConsumer());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Prefix, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
// When asserts are on, TURN ON not compare the VerifyModule
assert(CI->getCodeGenOpts().VerifyModule = 1);
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
Opts.ObjCNonFragileABI2 = 0;
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
if (Target.getTriple().getArch() == llvm::Triple::x86) {
Opts.ObjCNonFragileABI = 1;
} else {
Opts.ObjCNonFragileABI = 0;
}
if (Target.getTriple().isOSDarwin()) {
Opts.NeXTRuntime = 1;
} else {
Opts.NeXTRuntime = 0;
}
}
} // end namespace
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "ChainedConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), 0, argc, argv, llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
PragmaNamespace* Pragma,
int argc,
const char* const *argv,
const char* llvmdir){
// main's argv[0] is skipped!
if (!Pragma) {
Pragma = new PragmaNamespace("cling");
}
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
//
// If not set, exception handling will not be turned on
llvm::JITExceptionHandling = true;
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path = CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Needed when we call CreateFromArgs
CI->createDiagnostics(0, 0);
CompilerInvocation::CreateFromArgs
(CI->getInvocation(), argv, argv + argc, CI->getDiagnostics());
// Reset the diagnostics options that came from CreateFromArgs
DiagnosticOptions& DiagOpts = CI->getDiagnosticOpts();
DiagOpts.ShowColors = 1;
DiagnosticConsumer* Client = new TextDiagnosticPrinter(llvm::errs(), DiagOpts);
CI->createDiagnostics(0, 0, Client);
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
if (CI->getHeaderSearchOpts().UseBuiltinIncludes &&
CI->getHeaderSearchOpts().ResourceDir.empty()) {
CI->getHeaderSearchOpts().ResourceDir = resource_path.str();
}
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
CI->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.AddPragmaHandler(Pragma);
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOptions());
/*NoBuiltins = */ //true);
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(), 0);
CI->setASTContext(Ctx);
//CI->getSourceManager().clearIDTables(); //do we really need it?
// Set up the ASTConsumers
CI->setASTConsumer(new ChainedConsumer());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Prefix, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
assert((CI->getCodeGenOpts().VerifyModule = 1) && "When asserts are on, let's also assert the module");
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
}
}
} // end namespace
<commit_msg>Initialize langopts more closely to what Tools.cpp (Clang::ConstructJob) is doing, to end up with a compatible LangOpt set in cling and PCHs.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/CIFactory.h"
#include "ChainedConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/LLVMContext.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
//
// Dummy function so we can use dladdr to find the executable path.
//
void locate_cling_executable()
{
}
CompilerInstance* CIFactory::createCI(llvm::StringRef code,
int argc,
const char* const *argv,
const char* llvmdir) {
return createCI(llvm::MemoryBuffer::getMemBuffer(code), 0, argc, argv, llvmdir);
}
CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,
PragmaNamespace* Pragma,
int argc,
const char* const *argv,
const char* llvmdir){
// main's argv[0] is skipped!
if (!Pragma) {
Pragma = new PragmaNamespace("cling");
}
// Create an instance builder, passing the llvmdir and arguments.
//
// Initialize the llvm library.
//
// If not set, exception handling will not be turned on
llvm::JITExceptionHandling = true;
llvm::InitializeNativeTarget();
llvm::InitializeAllAsmPrinters();
llvm::sys::Path resource_path;
if (llvmdir) {
resource_path = llvmdir;
resource_path.appendComponent("lib");
resource_path.appendComponent("clang");
resource_path.appendComponent(CLANG_VERSION_STRING);
} else {
// FIXME: The first arg really does need to be argv[0] on FreeBSD.
//
// Note: The second arg is not used for Apple, FreeBSD, Linux,
// or cygwin, and can only be used on systems which support
// the use of dladdr().
//
// Note: On linux and cygwin this uses /proc/self/exe to find the path.
//
// Note: On Apple it uses _NSGetExecutablePath().
//
// Note: On FreeBSD it uses getprogpath().
//
// Note: Otherwise it uses dladdr().
//
resource_path = CompilerInvocation::GetResourcesPath("cling",
(void*)(intptr_t) locate_cling_executable
);
}
// Create and setup a compiler instance.
CompilerInstance* CI = new CompilerInstance();
{
//
// Buffer the error messages while we process
// the compiler options.
//
// Needed when we call CreateFromArgs
CI->createDiagnostics(0, 0);
CompilerInvocation::CreateFromArgs
(CI->getInvocation(), argv, argv + argc, CI->getDiagnostics());
// Reset the diagnostics options that came from CreateFromArgs
DiagnosticOptions& DiagOpts = CI->getDiagnosticOpts();
DiagOpts.ShowColors = 1;
DiagnosticConsumer* Client = new TextDiagnosticPrinter(llvm::errs(), DiagOpts);
CI->createDiagnostics(0, 0, Client);
// Set the language options, which cling needs
SetClingCustomLangOpts(CI->getLangOpts());
if (CI->getHeaderSearchOpts().UseBuiltinIncludes &&
CI->getHeaderSearchOpts().ResourceDir.empty()) {
CI->getHeaderSearchOpts().ResourceDir = resource_path.str();
}
CI->getInvocation().getPreprocessorOpts().addMacroDef("__CLING__");
if (CI->getDiagnostics().hasErrorOccurred()) {
delete CI;
CI = 0;
return 0;
}
}
CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),
CI->getTargetOpts()));
if (!CI->hasTarget()) {
delete CI;
CI = 0;
return 0;
}
CI->getTarget().setForcedLangOptions(CI->getLangOpts());
SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());
// Set up source and file managers
CI->createFileManager();
CI->createSourceManager(CI->getFileManager());
// Set up the memory buffer
if (buffer)
CI->getSourceManager().createMainFileIDForMemBuffer(buffer);
// Set up the preprocessor
CI->createPreprocessor();
Preprocessor& PP = CI->getPreprocessor();
PP.AddPragmaHandler(Pragma);
PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
PP.getLangOptions());
/*NoBuiltins = */ //true);
// Set up the ASTContext
ASTContext *Ctx = new ASTContext(CI->getLangOpts(),
PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(),
PP.getSelectorTable(), PP.getBuiltinInfo(), 0);
CI->setASTContext(Ctx);
//CI->getSourceManager().clearIDTables(); //do we really need it?
// Set up the ASTConsumers
CI->setASTConsumer(new ChainedConsumer());
// Set up Sema
CodeCompleteConsumer* CCC = 0;
CI->createSema(TU_Prefix, CCC);
// Set CodeGen options
// CI->getCodeGenOpts().DebugInfo = 1; // want debug info
// CI->getCodeGenOpts().EmitDeclMetadata = 1; // For unloading, for later
CI->getCodeGenOpts().OptimizationLevel = 0; // see pure SSA, that comes out
assert((CI->getCodeGenOpts().VerifyModule = 1) && "When asserts are on, let's also assert the module");
return CI;
}
void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {
Opts.EmitAllDecls = 1;
Opts.ObjCNonFragileABI2 = 0;
Opts.Exceptions = 1;
Opts.CXXExceptions = 1;
Opts.Deprecated = 1;
}
void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,
const TargetInfo& Target) {
if (Target.getTriple().getOS() == llvm::Triple::Win32) {
Opts.MicrosoftExt = 1;
Opts.MSCVersion = 1300;
// Should fix http://llvm.org/bugs/show_bug.cgi?id=10528
Opts.DelayedTemplateParsing = 1;
} else {
Opts.MicrosoftExt = 0;
}
if (Target.getTriple().getArch() == llvm::Triple::x86) {
Opts.ObjCNonFragileABI = 1;
} else {
Opts.ObjCNonFragileABI = 0;
}
if (Target.getTriple().isOSDarwin()) {
Opts.NeXTRuntime = 1;
} else {
Opts.NeXTRuntime = 0;
}
}
} // end namespace
<|endoftext|>
|
<commit_before>/*
* Converts media wiki markup into plaintext
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string.h>
#include <pcre.h>
#include <math.h>
#include <dirent.h>
using namespace std;
char* substr(char* dest, const char* src, int start, int len, int n)
{
if(start >= n)
throw string("Start index outside of string.");
int actual_length = min(len, n-start);
strncpy(dest, &src[start], actual_length);
dest[actual_length] = '\0';
return dest;
}
typedef struct _State
{
int N; // input length
int pos; // current position in input
const char* markup; // the markup input we're converting
char* out;
int M; // maximum length of output
int pos_out;
string groups[10]; // will store regexp matches
} State;
class Textifier
{
private:
State state;
bool starts_with(string& str);
bool starts_with(const char* str);
const char* get_remaining();
char* get_current_out();
void skip_match();
void append_group_and_skip(int group);
void do_link();
void do_format();
void do_tag();
void do_meta();
void do_nowiki();
void do_heading();
void do_nested(string name, char open, char close);
bool get_link_boundaries(int& start, int& end, int& next);
string get_snippet();
string get_err(string name);
string* match(string name, pcre* regexp);
pcre* make_pcre(const char* expr, int options);
pcre* re_nowiki;
pcre* re_format;
pcre* re_heading;
public:
Textifier();
~Textifier();
char* textify(const char* markup, const int markup_len,
char* out, const int out_len);
void find_location(long& line, long& col);
};
Textifier::Textifier()
{
// Compile all the regexes we'll need
re_nowiki = make_pcre("^<nowiki>(.*?)</nowiki>", PCRE_MULTILINE | PCRE_DOTALL);
re_format = make_pcre("^('+)(.*?)\\1", 0);
re_heading = make_pcre("^(=+)\\s*(.+?)\\s*\\1", 0);
}
Textifier::~Textifier()
{
}
pcre* Textifier::make_pcre(const char* expr, int options)
{
const char* error;
int erroffset;
pcre *re = pcre_compile(expr, options, &error, &erroffset, NULL);
if(re == NULL) {
ostringstream os;
os << "PCRE compilation failed at offset " << erroffset << ": "
<< error << endl;
throw string(os.str());
}
return re;
}
bool Textifier::get_link_boundaries(int& start, int& end, int& next)
{
int i = state.pos; // current search position
int level = 0; // nesting level
do {
char ch = state.markup[i];
switch(ch) {
case '[':
if(level++ == 0)
start = i+1;
break;
case ']':
if(--level == 0)
end = i;
break;
case '|':
if(level == 1) { // does the pipe belong to current link or a nested one?
start = i+1;
end = start;
}
break;
default:
end++;
break;
}
i++;
} while(level > 0 &&
i < state.N &&
state.markup[i] != '\n');
next = i;
return level == 0; // if 0, then brackets match and this is a correct link
}
void Textifier::find_location(long& line, long& column)
{
line = 1;
column = 1;
for(int i = 0; i <= state.pos && i < state.N; i++) {
if(state.markup[i] == '\n')
line++;
else if(line == 1)
column++;
}
}
bool Textifier::starts_with(string& str)
{
return starts_with(str.c_str());
}
bool Textifier::starts_with(const char* str)
{
int i = state.pos;
int j = 0;
while(str[j] != '\0' &&
i < state.N) {
if(state.markup[i] != str[j])
return false;
i++;
j++;
}
return true;
}
string Textifier::get_snippet()
{
char snippet[30];
strncpy(snippet, get_remaining(), 30);
snippet[min(29, state.N-state.pos)] = '\0';
return string(snippet);
}
string Textifier::get_err(string name)
{
ostringstream os;
os << "Expected " << name << " at '" << get_snippet() << "'";
return os.str();
}
string* Textifier::match(string name, pcre* regexp)
{
const int ovector_size = 3*sizeof(state.groups)/sizeof(string);
int ovector[ovector_size];
int rc = pcre_exec(regexp, NULL, get_remaining(), state.N-state.pos, 0, 0, ovector, ovector_size);
if(rc == PCRE_ERROR_NOMATCH || rc == 0)
return NULL;
else if(rc < 0)
throw get_err(name);
// from pcredemo.c
for(int i = 0; i < rc; i++) {
const char *substring_start = get_remaining() + ovector[2*i];
int substring_length = ovector[2*i+1] - ovector[2*i];
char substr[substring_length+1];
strncpy(substr, substring_start, substring_length);
substr[substring_length]='\0';
state.groups[i].assign(substr);
}
return state.groups;
}
const char* Textifier::get_remaining()
{
return &state.markup[state.pos];
}
char* Textifier::get_current_out()
{
return &state.out[state.pos_out];
}
void Textifier::skip_match()
{
state.pos += state.groups[0].length();
}
void Textifier::append_group_and_skip(int group)
{
string* val = &state.groups[group];
strncpy(get_current_out(), val->c_str(), val->length());
state.pos += state.groups[0].length();
state.pos_out += val->length();
}
void Textifier::do_link()
{
int start, end, next;
if(get_link_boundaries(start, end, next)) {
char contents[end-start+1];
substr(contents, state.markup, start, end-start, state.N);
if(strchr(contents, ':') != NULL) {
// this is a link to the page in a different language:
// ignore it
state.pos = next;
}
else {
State state_copy = state;
textify(contents, end-start, &state.out[state.pos_out], state.M-state.pos_out);
state_copy.pos_out += state.pos_out;
state_copy.pos = next;
state = state_copy;
}
} else {
// Apparently mediawiki allows unmatched open brackets...
// If that's what we got, it's not a link.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
}
void Textifier::do_heading()
{
if(!match(string("heading"), re_heading))
{
// Not really a heading. Just copy to output.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
append_group_and_skip(2);
}
void Textifier::do_tag()
{
do_nested(string("tag"), '<', '>');
}
void Textifier::do_meta()
{
do_nested(string("meta"), '{', '}');
}
void Textifier::do_nowiki()
{
if(!match(string("nowiki"), re_nowiki))
throw get_err("nowiki");
skip_match();
}
void Textifier::do_format()
{
if(!match(string("format"), re_format))
throw get_err("format");
string* contents = &state.groups[2];
State state_copy = state; // Save state. A call to textify() will reset it.
// this call will write textified result directly to state.out
textify(contents->c_str(), contents->length(),
&state.out[state.pos_out], state.M-state.pos_out);
// output has possibly advanced since we saved the state
state_copy.pos_out += state.pos_out;
// restore state
state = state_copy;
skip_match();
}
void Textifier::do_nested(string name, char open, char close)
{
if(state.markup[state.pos] != open)
throw get_err(name);
int level = 0;
do {
if(state.markup[state.pos] == open) level++;
else if(state.markup[state.pos] == close) level--;
} while(state.pos++ < state.N && level > 0);
}
/**
* Converts state.markup to plain text. */
char* Textifier::textify(const char* markup, const int markup_len,
char* out, const int out_len)
{
this->state.N = markup_len;
this->state.pos = 0;
this->state.markup = markup;
this->state.out = out;
this->state.M = out_len;
this->state.pos_out = 0;
while(state.pos < state.N && state.pos_out < state.M) {
if(starts_with("<nowiki>"))
do_nowiki();
else if(starts_with("["))
do_link();
else if(starts_with("<"))
do_tag();
else if(starts_with("{{") || starts_with("{|"))
do_meta();
else if(starts_with("="))
do_heading();
else if(starts_with("''"))
do_format();
else {
if(state.pos_out == 0 ||
state.out[state.pos_out-1] != state.markup[state.pos] ||
state.markup[state.pos] != '\n')
out[state.pos_out++] = state.markup[state.pos++];
else
state.pos++;
}
}
out[state.pos_out] = '\0';
return out;
}
int main(int argc, char** argv)
{
if(argc != 2) {
cerr << "Usage: " << argv[0] << " input-file" << endl;
return 1;
}
char* path = argv[1];
ifstream file(path, ios::in|ios::ate);
long size = file.tellg();
char* markup = new char[size+1];
file.seekg(0, ios::beg);
file.read(markup, size);
markup[size] = '\0';
file.close();
Textifier tf;
const int markup_len = strlen(markup);
char* plaintext = new char[markup_len+1];
try {
cout << tf.textify(markup, markup_len, plaintext, markup_len) << endl;
}
catch(string err) {
long line;
long column;
tf.find_location(line, column);
cerr << "ERROR (" << path << ":" << line << ":" << column << ") " << err << endl;
return 1;
}
delete plaintext;
delete markup;
return 0;
}
<commit_msg>fail if input file does not exist<commit_after>/*
* Converts media wiki markup into plaintext
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string.h>
#include <pcre.h>
#include <math.h>
#include <dirent.h>
using namespace std;
char* substr(char* dest, const char* src, int start, int len, int n)
{
if(start >= n)
throw string("Start index outside of string.");
int actual_length = min(len, n-start);
strncpy(dest, &src[start], actual_length);
dest[actual_length] = '\0';
return dest;
}
typedef struct _State
{
int N; // input length
int pos; // current position in input
const char* markup; // the markup input we're converting
char* out;
int M; // maximum length of output
int pos_out;
string groups[10]; // will store regexp matches
} State;
class Textifier
{
private:
State state;
bool starts_with(string& str);
bool starts_with(const char* str);
const char* get_remaining();
char* get_current_out();
void skip_match();
void append_group_and_skip(int group);
void do_link();
void do_format();
void do_tag();
void do_meta();
void do_nowiki();
void do_heading();
void do_nested(string name, char open, char close);
bool get_link_boundaries(int& start, int& end, int& next);
string get_snippet();
string get_err(string name);
string* match(string name, pcre* regexp);
pcre* make_pcre(const char* expr, int options);
pcre* re_nowiki;
pcre* re_format;
pcre* re_heading;
public:
Textifier();
~Textifier();
char* textify(const char* markup, const int markup_len,
char* out, const int out_len);
void find_location(long& line, long& col);
};
Textifier::Textifier()
{
// Compile all the regexes we'll need
re_nowiki = make_pcre("^<nowiki>(.*?)</nowiki>", PCRE_MULTILINE | PCRE_DOTALL);
re_format = make_pcre("^('+)(.*?)\\1", 0);
re_heading = make_pcre("^(=+)\\s*(.+?)\\s*\\1", 0);
}
Textifier::~Textifier()
{
}
pcre* Textifier::make_pcre(const char* expr, int options)
{
const char* error;
int erroffset;
pcre *re = pcre_compile(expr, options, &error, &erroffset, NULL);
if(re == NULL) {
ostringstream os;
os << "PCRE compilation failed at offset " << erroffset << ": "
<< error << endl;
throw string(os.str());
}
return re;
}
bool Textifier::get_link_boundaries(int& start, int& end, int& next)
{
int i = state.pos; // current search position
int level = 0; // nesting level
do {
char ch = state.markup[i];
switch(ch) {
case '[':
if(level++ == 0)
start = i+1;
break;
case ']':
if(--level == 0)
end = i;
break;
case '|':
if(level == 1) { // does the pipe belong to current link or a nested one?
start = i+1;
end = start;
}
break;
default:
end++;
break;
}
i++;
} while(level > 0 &&
i < state.N &&
state.markup[i] != '\n');
next = i;
return level == 0; // if 0, then brackets match and this is a correct link
}
void Textifier::find_location(long& line, long& column)
{
line = 1;
column = 1;
for(int i = 0; i <= state.pos && i < state.N; i++) {
if(state.markup[i] == '\n')
line++;
else if(line == 1)
column++;
}
}
bool Textifier::starts_with(string& str)
{
return starts_with(str.c_str());
}
bool Textifier::starts_with(const char* str)
{
int i = state.pos;
int j = 0;
while(str[j] != '\0' &&
i < state.N) {
if(state.markup[i] != str[j])
return false;
i++;
j++;
}
return true;
}
string Textifier::get_snippet()
{
char snippet[30];
strncpy(snippet, get_remaining(), 30);
snippet[min(29, state.N-state.pos)] = '\0';
return string(snippet);
}
string Textifier::get_err(string name)
{
ostringstream os;
os << "Expected " << name << " at '" << get_snippet() << "'";
return os.str();
}
string* Textifier::match(string name, pcre* regexp)
{
const int ovector_size = 3*sizeof(state.groups)/sizeof(string);
int ovector[ovector_size];
int rc = pcre_exec(regexp, NULL, get_remaining(), state.N-state.pos, 0, 0, ovector, ovector_size);
if(rc == PCRE_ERROR_NOMATCH || rc == 0)
return NULL;
else if(rc < 0)
throw get_err(name);
// from pcredemo.c
for(int i = 0; i < rc; i++) {
const char *substring_start = get_remaining() + ovector[2*i];
int substring_length = ovector[2*i+1] - ovector[2*i];
char substr[substring_length+1];
strncpy(substr, substring_start, substring_length);
substr[substring_length]='\0';
state.groups[i].assign(substr);
}
return state.groups;
}
const char* Textifier::get_remaining()
{
return &state.markup[state.pos];
}
char* Textifier::get_current_out()
{
return &state.out[state.pos_out];
}
void Textifier::skip_match()
{
state.pos += state.groups[0].length();
}
void Textifier::append_group_and_skip(int group)
{
string* val = &state.groups[group];
strncpy(get_current_out(), val->c_str(), val->length());
state.pos += state.groups[0].length();
state.pos_out += val->length();
}
void Textifier::do_link()
{
int start, end, next;
if(get_link_boundaries(start, end, next)) {
char contents[end-start+1];
substr(contents, state.markup, start, end-start, state.N);
if(strchr(contents, ':') != NULL) {
// this is a link to the page in a different language:
// ignore it
state.pos = next;
}
else {
State state_copy = state;
textify(contents, end-start, &state.out[state.pos_out], state.M-state.pos_out);
state_copy.pos_out += state.pos_out;
state_copy.pos = next;
state = state_copy;
}
} else {
// Apparently mediawiki allows unmatched open brackets...
// If that's what we got, it's not a link.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
}
void Textifier::do_heading()
{
if(!match(string("heading"), re_heading))
{
// Not really a heading. Just copy to output.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
append_group_and_skip(2);
}
void Textifier::do_tag()
{
do_nested(string("tag"), '<', '>');
}
void Textifier::do_meta()
{
do_nested(string("meta"), '{', '}');
}
void Textifier::do_nowiki()
{
if(!match(string("nowiki"), re_nowiki))
throw get_err("nowiki");
skip_match();
}
void Textifier::do_format()
{
if(!match(string("format"), re_format))
throw get_err("format");
string* contents = &state.groups[2];
State state_copy = state; // Save state. A call to textify() will reset it.
// this call will write textified result directly to state.out
textify(contents->c_str(), contents->length(),
&state.out[state.pos_out], state.M-state.pos_out);
// output has possibly advanced since we saved the state
state_copy.pos_out += state.pos_out;
// restore state
state = state_copy;
skip_match();
}
void Textifier::do_nested(string name, char open, char close)
{
if(state.markup[state.pos] != open)
throw get_err(name);
int level = 0;
do {
if(state.markup[state.pos] == open) level++;
else if(state.markup[state.pos] == close) level--;
} while(state.pos++ < state.N && level > 0);
}
/**
* Converts state.markup to plain text. */
char* Textifier::textify(const char* markup, const int markup_len,
char* out, const int out_len)
{
this->state.N = markup_len;
this->state.pos = 0;
this->state.markup = markup;
this->state.out = out;
this->state.M = out_len;
this->state.pos_out = 0;
while(state.pos < state.N && state.pos_out < state.M) {
if(starts_with("<nowiki>"))
do_nowiki();
else if(starts_with("["))
do_link();
else if(starts_with("<"))
do_tag();
else if(starts_with("{{") || starts_with("{|"))
do_meta();
else if(starts_with("="))
do_heading();
else if(starts_with("''"))
do_format();
else {
if(state.pos_out == 0 ||
state.out[state.pos_out-1] != state.markup[state.pos] ||
state.markup[state.pos] != '\n')
out[state.pos_out++] = state.markup[state.pos++];
else
state.pos++;
}
}
out[state.pos_out] = '\0';
return out;
}
int main(int argc, char** argv)
{
if(argc != 2) {
cerr << "Usage: " << argv[0] << " input-file" << endl;
return 1;
}
char* path = argv[1];
ifstream file(path, ios::in|ios::ate);
if(!file) {
cerr << "The file '" << path << "' does not exist" << endl;
return 1;
}
long size = file.tellg();
char* markup = new char[size+1];
file.seekg(0, ios::beg);
file.read(markup, size);
markup[size] = '\0';
file.close();
Textifier tf;
const int markup_len = strlen(markup);
char* plaintext = new char[markup_len+1];
try {
cout << tf.textify(markup, markup_len, plaintext, markup_len) << endl;
}
catch(string err) {
long line;
long column;
tf.find_location(line, column);
cerr << "ERROR (" << path << ":" << line << ":" << column << ") " << err << endl;
return 1;
}
delete plaintext;
delete markup;
return 0;
}
<|endoftext|>
|
<commit_before>//===--- TerminalDisplayWin.h - Output To Windows Console -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface for writing to a Windows console
// i.e. cmd.exe.
//
// Axel Naumann <[email protected]>, 2011-05-12
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include "textinput/TerminalDisplayWin.h"
#include "textinput/Color.h"
#include <assert.h>
namespace textinput {
TerminalDisplayWin::TerminalDisplayWin():
TerminalDisplay(false), fStartLine(0), fIsAttached(false),
fDefaultAttributes(0), fOldCodePage(::GetConsoleOutputCP()) {
DWORD mode;
SetIsTTY(::GetConsoleMode(::GetStdHandle(STD_INPUT_HANDLE), &mode) != 0);
fOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
bool isConsole = ::GetConsoleMode(fOut, &fOldMode) != 0;
if (!isConsole) {
// Prevent redirection from stealing our console handle,
// simply open our own.
fOut = ::CreateFileA("CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
::GetConsoleMode(fOut, &fOldMode);
} else
::SetConsoleOutputCP(65001); // Force UTF-8 output
CONSOLE_SCREEN_BUFFER_INFO csbi;
::GetConsoleScreenBufferInfo(fOut, &csbi);
fDefaultAttributes = csbi.wAttributes;
assert(fDefaultAttributes != 0 && "~TerminalDisplayWin broken");
fMyMode = fOldMode | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT;
HandleResizeEvent();
}
TerminalDisplayWin::~TerminalDisplayWin() {
if (fDefaultAttributes) {
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
// We allocated CONOUT$:
CloseHandle(fOut);
} else
::SetConsoleOutputCP(fOldCodePage);
}
void
TerminalDisplayWin::HandleResizeEvent() {
if (IsTTY()) {
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("resize / getting console info");
return;
}
SetWidth(Info.dwSize.X);
}
}
void
TerminalDisplayWin::SetColor(char CIdx, const Color& C) {
WORD Attribs = 0;
// There is no underline since DOS has died.
if (C.fModifiers & Color::kModUnderline) Attribs |= BACKGROUND_INTENSITY;
if (C.fModifiers & Color::kModBold) Attribs |= FOREGROUND_INTENSITY;
if (C.fR > 64) Attribs |= FOREGROUND_RED;
if (C.fG > 64) Attribs |= FOREGROUND_GREEN;
if (C.fB > 64) Attribs |= FOREGROUND_BLUE;
// if CIdx is 0 (default) then use the original console text color
// (instead of the greyish one)
if (CIdx == 0)
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
else
::SetConsoleTextAttribute(fOut, Attribs);
}
void
TerminalDisplayWin::CheckCursorPos() {
if (!IsTTY()) return;
// Did something print something on the screen?
// I.e. did the cursor move?
CONSOLE_SCREEN_BUFFER_INFO CSI;
if (::GetConsoleScreenBufferInfo(fOut, &CSI)) {
if (CSI.dwCursorPosition.X != fWritePos.fCol
|| CSI.dwCursorPosition.Y != fWritePos.fLine + fStartLine) {
fStartLine = CSI.dwCursorPosition.Y;
if (CSI.dwCursorPosition.X) {
// fStartLine may be a couple of lines higher (or more precisely
// the number of written lines higher)
fStartLine -= fWritePos.fLine;
}
fWritePos.fCol = 0;
fWritePos.fLine = 0;
}
}
}
void
TerminalDisplayWin::Move(Pos P) {
CheckCursorPos();
MoveInternal(P);
fWritePos = P;
}
void
TerminalDisplayWin::MoveInternal(Pos P) {
if (IsTTY()) {
COORD C = {P.fCol, P.fLine + fStartLine};
::SetConsoleCursorPosition(fOut, C);
}
}
void
TerminalDisplayWin::MoveFront() {
Pos P(fWritePos);
P.fCol = 0;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveUp(size_t nLines /* = 1 */) {
Pos P(fWritePos);
--P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveDown(size_t nLines /* = 1 */) {
Pos P(fWritePos);
++P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveRight(size_t nCols /* = 1 */) {
Pos P(fWritePos);
++P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveLeft(size_t nCols /* = 1 */) {
Pos P(fWritePos);
--P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::EraseToRight() {
DWORD NumWritten;
COORD C = {fWritePos.fCol, fWritePos.fLine + fStartLine};
::FillConsoleOutputCharacterA(fOut, ' ', GetWidth() - C.X, C,
&NumWritten);
// It wraps, so move up and reset WritePos:
//MoveUp();
//++WritePos.Line;
}
void
TerminalDisplayWin::WriteRawString(const char *text, size_t len) {
DWORD NumWritten = 0;
if (IsTTY()) {
WriteConsoleA(fOut, text, (DWORD) len, &NumWritten, NULL);
} else {
WriteFile(fOut, text, (DWORD) len, &NumWritten, NULL);
}
if (NumWritten != len) {
ShowError("writing to output");
}
}
void
TerminalDisplayWin::Attach() {
// set to noecho
if (fIsAttached || !IsTTY()) return;
if (!::SetConsoleMode(fOut, fMyMode)) {
ShowError("attaching to console output");
}
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("attaching / getting console info");
} else {
fStartLine = Info.dwCursorPosition.Y;
if (Info.dwCursorPosition.X) {
// Whooa - where are we?! Newline and cross fingers:
WriteRawString("\n", 1);
++fStartLine;
}
}
fIsAttached = true;
}
void
TerminalDisplayWin::Detach() {
if (!fIsAttached || !IsTTY()) return;
if (!SetConsoleMode(fOut, fOldMode)) {
ShowError("detaching to console output");
}
TerminalDisplay::Detach();
fIsAttached = false;
}
void
TerminalDisplayWin::ShowError(const char* Where) const {
DWORD Err = GetLastError();
LPVOID MsgBuf = 0;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &MsgBuf, 0, NULL);
printf("Error %d in textinput::TerminalDisplayWin %s: %s\n", Err, Where, MsgBuf);
LocalFree(MsgBuf);
}
}
#endif // ifdef _WIN32
<commit_msg>disambiguate the else branch<commit_after>//===--- TerminalDisplayWin.h - Output To Windows Console -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface for writing to a Windows console
// i.e. cmd.exe.
//
// Axel Naumann <[email protected]>, 2011-05-12
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include "textinput/TerminalDisplayWin.h"
#include "textinput/Color.h"
#include <assert.h>
namespace textinput {
TerminalDisplayWin::TerminalDisplayWin():
TerminalDisplay(false), fStartLine(0), fIsAttached(false),
fDefaultAttributes(0), fOldCodePage(::GetConsoleOutputCP()) {
DWORD mode;
SetIsTTY(::GetConsoleMode(::GetStdHandle(STD_INPUT_HANDLE), &mode) != 0);
fOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
bool isConsole = ::GetConsoleMode(fOut, &fOldMode) != 0;
if (!isConsole) {
// Prevent redirection from stealing our console handle,
// simply open our own.
fOut = ::CreateFileA("CONOUT$", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
::GetConsoleMode(fOut, &fOldMode);
} else {
::SetConsoleOutputCP(65001); // Force UTF-8 output
}
CONSOLE_SCREEN_BUFFER_INFO csbi;
::GetConsoleScreenBufferInfo(fOut, &csbi);
fDefaultAttributes = csbi.wAttributes;
assert(fDefaultAttributes != 0 && "~TerminalDisplayWin broken");
fMyMode = fOldMode | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT;
HandleResizeEvent();
}
TerminalDisplayWin::~TerminalDisplayWin() {
if (fDefaultAttributes) {
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
// We allocated CONOUT$:
CloseHandle(fOut);
} else
::SetConsoleOutputCP(fOldCodePage);
}
void
TerminalDisplayWin::HandleResizeEvent() {
if (IsTTY()) {
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("resize / getting console info");
return;
}
SetWidth(Info.dwSize.X);
}
}
void
TerminalDisplayWin::SetColor(char CIdx, const Color& C) {
WORD Attribs = 0;
// There is no underline since DOS has died.
if (C.fModifiers & Color::kModUnderline) Attribs |= BACKGROUND_INTENSITY;
if (C.fModifiers & Color::kModBold) Attribs |= FOREGROUND_INTENSITY;
if (C.fR > 64) Attribs |= FOREGROUND_RED;
if (C.fG > 64) Attribs |= FOREGROUND_GREEN;
if (C.fB > 64) Attribs |= FOREGROUND_BLUE;
// if CIdx is 0 (default) then use the original console text color
// (instead of the greyish one)
if (CIdx == 0)
::SetConsoleTextAttribute(fOut, fDefaultAttributes);
else
::SetConsoleTextAttribute(fOut, Attribs);
}
void
TerminalDisplayWin::CheckCursorPos() {
if (!IsTTY()) return;
// Did something print something on the screen?
// I.e. did the cursor move?
CONSOLE_SCREEN_BUFFER_INFO CSI;
if (::GetConsoleScreenBufferInfo(fOut, &CSI)) {
if (CSI.dwCursorPosition.X != fWritePos.fCol
|| CSI.dwCursorPosition.Y != fWritePos.fLine + fStartLine) {
fStartLine = CSI.dwCursorPosition.Y;
if (CSI.dwCursorPosition.X) {
// fStartLine may be a couple of lines higher (or more precisely
// the number of written lines higher)
fStartLine -= fWritePos.fLine;
}
fWritePos.fCol = 0;
fWritePos.fLine = 0;
}
}
}
void
TerminalDisplayWin::Move(Pos P) {
CheckCursorPos();
MoveInternal(P);
fWritePos = P;
}
void
TerminalDisplayWin::MoveInternal(Pos P) {
if (IsTTY()) {
COORD C = {P.fCol, P.fLine + fStartLine};
::SetConsoleCursorPosition(fOut, C);
}
}
void
TerminalDisplayWin::MoveFront() {
Pos P(fWritePos);
P.fCol = 0;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveUp(size_t nLines /* = 1 */) {
Pos P(fWritePos);
--P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveDown(size_t nLines /* = 1 */) {
Pos P(fWritePos);
++P.fLine;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveRight(size_t nCols /* = 1 */) {
Pos P(fWritePos);
++P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::MoveLeft(size_t nCols /* = 1 */) {
Pos P(fWritePos);
--P.fCol;
MoveInternal(P);
}
void
TerminalDisplayWin::EraseToRight() {
DWORD NumWritten;
COORD C = {fWritePos.fCol, fWritePos.fLine + fStartLine};
::FillConsoleOutputCharacterA(fOut, ' ', GetWidth() - C.X, C,
&NumWritten);
// It wraps, so move up and reset WritePos:
//MoveUp();
//++WritePos.Line;
}
void
TerminalDisplayWin::WriteRawString(const char *text, size_t len) {
DWORD NumWritten = 0;
if (IsTTY()) {
WriteConsoleA(fOut, text, (DWORD) len, &NumWritten, NULL);
} else {
WriteFile(fOut, text, (DWORD) len, &NumWritten, NULL);
}
if (NumWritten != len) {
ShowError("writing to output");
}
}
void
TerminalDisplayWin::Attach() {
// set to noecho
if (fIsAttached || !IsTTY()) return;
if (!::SetConsoleMode(fOut, fMyMode)) {
ShowError("attaching to console output");
}
CONSOLE_SCREEN_BUFFER_INFO Info;
if (!::GetConsoleScreenBufferInfo(fOut, &Info)) {
ShowError("attaching / getting console info");
} else {
fStartLine = Info.dwCursorPosition.Y;
if (Info.dwCursorPosition.X) {
// Whooa - where are we?! Newline and cross fingers:
WriteRawString("\n", 1);
++fStartLine;
}
}
fIsAttached = true;
}
void
TerminalDisplayWin::Detach() {
if (!fIsAttached || !IsTTY()) return;
if (!SetConsoleMode(fOut, fOldMode)) {
ShowError("detaching to console output");
}
TerminalDisplay::Detach();
fIsAttached = false;
}
void
TerminalDisplayWin::ShowError(const char* Where) const {
DWORD Err = GetLastError();
LPVOID MsgBuf = 0;
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &MsgBuf, 0, NULL);
printf("Error %d in textinput::TerminalDisplayWin %s: %s\n", Err, Where, MsgBuf);
LocalFree(MsgBuf);
}
}
#endif // ifdef _WIN32
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2017-2018 Andrew Depke
*/
#include "WindowsProcess.h"
#include <Windows.h>
#include <Psapi.h>
namespace Red
{
bool GetProcessModules(std::vector<ProcessModule>* Output)
{
if (!Output)
{
return false;
}
HMODULE Modules[1024];
HANDLE Process = GetCurrentProcess();
DWORD BytesNeeded;
if (EnumProcessModules(Process, Modules, sizeof(Modules), &BytesNeeded))
{
for (int Iter = 0; Iter < (BytesNeeded / sizeof(HMODULE)); ++Iter)
{
ProcessModule Module;
char ModuleName[MAX_PATH];
if (GetModuleFileNameA(Modules[Iter], ModuleName, sizeof(ModuleName)))
{
Module.Name = ModuleName;
}
MODULEINFO Info;
if (GetModuleInformation(GetCurrentProcess(), Modules[Iter], &Info, sizeof(Info)))
{
DWORD64* AddressDWORD64 = static_cast<DWORD64*>(Info.lpBaseOfDll);
char AddressBuffer[64];
snprintf(AddressBuffer, sizeof(AddressBuffer), "0x%016llX", static_cast<unsigned long long>(*AddressDWORD64));
Module.BaseAddress = AddressBuffer;
}
WIN32_FILE_ATTRIBUTE_DATA FileInfo;
if (GetFileAttributesExA(ModuleName, GetFileExInfoStandard, &FileInfo))
{
LARGE_INTEGER FileSizeBytes;
FileSizeBytes.HighPart = FileInfo.nFileSizeHigh;
FileSizeBytes.LowPart = FileInfo.nFileSizeLow;
Module.FileSize = FileSizeBytes.QuadPart;
}
Output->push_back(Module);
}
}
else
{
return false;
}
return true;
}
} // namespace Red<commit_msg>Fixed Sign Mismatch Warning<commit_after>/*
Copyright (c) 2017-2018 Andrew Depke
*/
#include "WindowsProcess.h"
#include <Windows.h>
#include <Psapi.h>
namespace Red
{
bool GetProcessModules(std::vector<ProcessModule>* Output)
{
if (!Output)
{
return false;
}
HMODULE Modules[1024];
HANDLE Process = GetCurrentProcess();
DWORD BytesNeeded;
if (EnumProcessModules(Process, Modules, sizeof(Modules), &BytesNeeded))
{
for (unsigned int Iter = 0; Iter < (BytesNeeded / sizeof(HMODULE)); ++Iter)
{
ProcessModule Module;
char ModuleName[MAX_PATH];
if (GetModuleFileNameA(Modules[Iter], ModuleName, sizeof(ModuleName)))
{
Module.Name = ModuleName;
}
MODULEINFO Info;
if (GetModuleInformation(GetCurrentProcess(), Modules[Iter], &Info, sizeof(Info)))
{
DWORD64* AddressDWORD64 = static_cast<DWORD64*>(Info.lpBaseOfDll);
char AddressBuffer[64];
snprintf(AddressBuffer, sizeof(AddressBuffer), "0x%016llX", static_cast<unsigned long long>(*AddressDWORD64));
Module.BaseAddress = AddressBuffer;
}
WIN32_FILE_ATTRIBUTE_DATA FileInfo;
if (GetFileAttributesExA(ModuleName, GetFileExInfoStandard, &FileInfo))
{
LARGE_INTEGER FileSizeBytes;
FileSizeBytes.HighPart = FileInfo.nFileSizeHigh;
FileSizeBytes.LowPart = FileInfo.nFileSizeLow;
Module.FileSize = FileSizeBytes.QuadPart;
}
Output->push_back(Module);
}
}
else
{
return false;
}
return true;
}
} // namespace Red<|endoftext|>
|
<commit_before>/** @file
Catch-based unit tests for MIOBufferWriter class.
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <cstdint>
struct IOBufferBlock {
std::int64_t write_avail();
char *end();
void fill(int64_t);
};
struct MIOBuffer {
IOBufferBlock *first_write_block();
void add_block();
};
#define UNIT_TEST_BUFFER_WRITER
#include "I_MIOBufferWriter.h"
IOBufferBlock iobb[1];
int iobbIdx{0};
const int BlockSize = 11 * 11;
char block[BlockSize];
int blockUsed{0};
std::int64_t
IOBufferBlock::write_avail()
{
REQUIRE(this == (iobb + iobbIdx));
return BlockSize - blockUsed;
}
char *
IOBufferBlock::end()
{
REQUIRE(this == (iobb + iobbIdx));
return block + blockUsed;
}
void
IOBufferBlock::fill(int64_t len)
{
static std::uint8_t dataCheck;
REQUIRE(this == (iobb + iobbIdx));
while (len-- and (blockUsed < BlockSize)) {
REQUIRE(block[blockUsed] == static_cast<char>(dataCheck));
++blockUsed;
dataCheck += 7;
}
REQUIRE(len == -1);
}
MIOBuffer theMIOBuffer;
IOBufferBlock *
MIOBuffer::first_write_block()
{
REQUIRE(this == &theMIOBuffer);
REQUIRE(blockUsed <= BlockSize);
if (blockUsed == BlockSize) {
return nullptr;
}
return iobb + iobbIdx;
}
void
MIOBuffer::add_block()
{
REQUIRE(this == &theMIOBuffer);
REQUIRE(blockUsed == BlockSize);
blockUsed = 0;
++iobbIdx;
}
std::string
genData(int numBytes)
{
static std::uint8_t genData;
std::string s(numBytes, ' ');
for (int i{0}; i < numBytes; ++i) {
s[i] = genData;
genData += 7;
}
return s;
}
void
writeOnce(MIOBufferWriter &bw, std::size_t len)
{
static bool toggle;
std::string s{genData(len)};
if (len == 1) {
bw.write(s[0]);
} else if (toggle) {
std::size_t cap{bw.auxBufferCapacity()};
if (cap >= len) {
memcpy(bw.auxBuffer(), s.data(), len);
bw.write(len);
} else {
memcpy(bw.auxBuffer(), s.data(), cap);
bw.write(cap);
bw.write(s.data() + cap, len - cap);
}
} else {
bw.write(s.data(), len);
}
toggle = !toggle;
REQUIRE(bw.auxBufferCapacity() <= BlockSize);
}
class InkAssertExcept
{
};
TEST_CASE("MIOBufferWriter", "[MIOBW]")
{
MIOBufferWriter bw(theMIOBuffer);
REQUIRE(bw.auxBufferCapacity() == BlockSize);
writeOnce(bw, 0);
writeOnce(bw, 1);
writeOnce(bw, 1);
writeOnce(bw, 1);
writeOnce(bw, 10);
writeOnce(bw, 1000);
writeOnce(bw, 1);
writeOnce(bw, 0);
writeOnce(bw, 1);
writeOnce(bw, 2000);
writeOnce(bw, 69);
writeOnce(bw, 666);
for (int i = 0; i < 3000; i += 13) {
writeOnce(bw, i);
}
writeOnce(bw, 0);
writeOnce(bw, 1);
REQUIRE(bw.extent() == ((iobbIdx * BlockSize) + blockUsed));
// These tests don't work properly with clang for some reason.
#if !defined(__clang__)
try {
bw.write(bw.auxBufferCapacity() + 1);
REQUIRE(false);
} catch (InkAssertExcept) {
REQUIRE(true);
}
try {
bw.data();
REQUIRE(false);
} catch (InkAssertExcept) {
REQUIRE(true);
}
#endif
}
void
_ink_assert(const char *a, const char *f, int l)
{
throw InkAssertExcept();
}
<commit_msg>Remove MIOBufferWriter unit tests that throw exceptions.<commit_after>/** @file
Catch-based unit tests for MIOBufferWriter class.
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <cstdint>
#include <cstdlib>
struct IOBufferBlock {
std::int64_t write_avail();
char *end();
void fill(int64_t);
};
struct MIOBuffer {
IOBufferBlock *first_write_block();
void add_block();
};
#define UNIT_TEST_BUFFER_WRITER
#include "I_MIOBufferWriter.h"
IOBufferBlock iobb[1];
int iobbIdx{0};
const int BlockSize = 11 * 11;
char block[BlockSize];
int blockUsed{0};
std::int64_t
IOBufferBlock::write_avail()
{
REQUIRE(this == (iobb + iobbIdx));
return BlockSize - blockUsed;
}
char *
IOBufferBlock::end()
{
REQUIRE(this == (iobb + iobbIdx));
return block + blockUsed;
}
void
IOBufferBlock::fill(int64_t len)
{
static std::uint8_t dataCheck;
REQUIRE(this == (iobb + iobbIdx));
while (len-- and (blockUsed < BlockSize)) {
REQUIRE(block[blockUsed] == static_cast<char>(dataCheck));
++blockUsed;
dataCheck += 7;
}
REQUIRE(len == -1);
}
MIOBuffer theMIOBuffer;
IOBufferBlock *
MIOBuffer::first_write_block()
{
REQUIRE(this == &theMIOBuffer);
REQUIRE(blockUsed <= BlockSize);
if (blockUsed == BlockSize) {
return nullptr;
}
return iobb + iobbIdx;
}
void
MIOBuffer::add_block()
{
REQUIRE(this == &theMIOBuffer);
REQUIRE(blockUsed == BlockSize);
blockUsed = 0;
++iobbIdx;
}
std::string
genData(int numBytes)
{
static std::uint8_t genData;
std::string s(numBytes, ' ');
for (int i{0}; i < numBytes; ++i) {
s[i] = genData;
genData += 7;
}
return s;
}
void
writeOnce(MIOBufferWriter &bw, std::size_t len)
{
static bool toggle;
std::string s{genData(len)};
if (len == 1) {
bw.write(s[0]);
} else if (toggle) {
std::size_t cap{bw.auxBufferCapacity()};
if (cap >= len) {
memcpy(bw.auxBuffer(), s.data(), len);
bw.write(len);
} else {
memcpy(bw.auxBuffer(), s.data(), cap);
bw.write(cap);
bw.write(s.data() + cap, len - cap);
}
} else {
bw.write(s.data(), len);
}
toggle = !toggle;
REQUIRE(bw.auxBufferCapacity() <= BlockSize);
}
class InkAssertExcept
{
};
TEST_CASE("MIOBufferWriter", "[MIOBW]")
{
MIOBufferWriter bw(theMIOBuffer);
REQUIRE(bw.auxBufferCapacity() == BlockSize);
writeOnce(bw, 0);
writeOnce(bw, 1);
writeOnce(bw, 1);
writeOnce(bw, 1);
writeOnce(bw, 10);
writeOnce(bw, 1000);
writeOnce(bw, 1);
writeOnce(bw, 0);
writeOnce(bw, 1);
writeOnce(bw, 2000);
writeOnce(bw, 69);
writeOnce(bw, 666);
for (int i = 0; i < 3000; i += 13) {
writeOnce(bw, i);
}
writeOnce(bw, 0);
writeOnce(bw, 1);
REQUIRE(bw.extent() == ((iobbIdx * BlockSize) + blockUsed));
}
void
_ink_assert(const char *a, const char *f, int l)
{
std::exit(1);
}
<|endoftext|>
|
<commit_before>//// Fancy ncurses terminal for calculators
//// Author: David P. Sicilia, June 2016
#include <ncurses.h>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <string.h>
#include <dlfcn.h>
#include <stdlib.h>
#include "assert.hpp"
#include "scope_exit.hpp"
#include "line_editor.hpp"
#include "input_view.hpp"
#include "icalcterm/icalcterm.h"
using namespace std;
struct Entry
{
std::string one_line;
std::vector<std::string> grid;
};
struct Stripe
{
Entry e;
bool is_left;
int y;
int x;
};
auto render_stripe( int width, Stripe const& s ) -> std::vector<std::string>
{
ASSERT( s.x >= 0 )
ASSERT( s.y >= 0 )
auto out = std::vector<std::string>( s.y );
//auto out = std::vector<std::string>( s.y+2 );
int start_x = s.is_left ? 1 : width-1-s.x;
ASSERT( start_x >= 0 )
auto pad = std::string( " " ); //start_x, ' ' );
ASSERT( width-start_x-s.x >= 0 )
auto end_pad = std::string( " " ); //width-start_x-s.x, ' ' );
for( int i = 0; i < s.y; ++i )
out[i] = pad + s.e.grid[i] + end_pad;
//out[i+1] = pad + s.e.grid[i] + end_pad;
//out[0] = pad + std::string( s.x, ' ' ) + end_pad;
//out[s.y+1] = pad + std::string( s.x, ' ' ) + end_pad;
return out;
}
auto draw_stripe( int width, int start_y, bool highlight, Stripe const& s ) -> void
{
auto text = render_stripe( width, s );
//if( highlight ) attroff( A_REVERSE );
if( highlight ) attron( A_REVERSE );
for( int i = text.size(); i > 0; --i ) {
if( start_y-i < 0 )
break;
ASSERT( start_y-int(text.size())+i >= 0 )
if( s.is_left )
mvprintw( start_y-text.size()+i, 1, text[i-1].c_str() );
else
mvprintw( start_y-text.size()+i, width-s.x-1, text[i-1].c_str() );
}
//if( highlight ) attron( A_REVERSE );
if( highlight ) attroff( A_REVERSE );
}
auto draw_stripes( int highlight, std::vector<Stripe> const& v ) -> void
{
int height = 0, width = 0;
getmaxyx( stdscr, height, width );
width -= 2;
(void)height;
int start_y = height-6;
ASSERT( start_y >= 0 )
int highlight_j = v.size() - highlight;
ASSERT( highlight_j >= 0 )
//for( int j = start_y; j >= 0; --j )
for( int j = start_y; j >= 1; --j )
mvhline( j, 1, ' ', width );
for( int j = v.size(); j > 0; --j ) {
if( start_y < 0 )
break;
Stripe const& s = v[j-1];
bool highlight = (j == highlight_j);
draw_stripe( width, start_y, highlight, s );
//start_y -= (s.y+2);
start_y -= (s.y);
}
}
std::vector<Stripe> vs = { };
#define GET_FUNC_SYM( sym ) \
sym ## _t sym; \
*(void**)(&sym) = dlsym( calc, #sym ); \
char const* STRING_JOIN( error__, __LINE__ ) = dlerror(); \
if( STRING_JOIN( error__, __LINE__) ) { \
fprintf( stderr, "%s\n", STRING_JOIN( error__, __LINE__) ); \
return 1; \
}
#ifdef OS_LINUX
char const* deflibname = "libdefcalc.so";
#else
#ifdef OS_OSX
char const* deflibname = "libdefcalc.dylib";
#endif
#endif
int _main(int argc, char* argv[])
{
char const* libname;
if( argc == 1 )
libname = deflibname;
else
libname = argv[1];
//printf("Loading library: %s\n", libname);
void* calc = dlopen( libname, RTLD_NOW );
if( !calc ) {
fprintf( stderr, "Unable to load library %s:\n%s\n", libname, dlerror() );
return 1;
}
SCOPE_EXIT( dlclose( calc ) )
GET_FUNC_SYM( CI_init )
GET_FUNC_SYM( CI_config )
GET_FUNC_SYM( CI_submit )
GET_FUNC_SYM( CI_result_free )
CI_init( NULL );
initscr();
SCOPE_EXIT( endwin() )
raw();
nonl();
noecho();
keypad(stdscr, TRUE);
int ch;
int highlight = -1;
int height = 0, width = 0;
getmaxyx( stdscr, height, width );
//attron( A_REVERSE );
for( int i = 0; i < height; ++i )
mvhline( i, 0, ' ', width );
draw_stripes( -1, vs );
LineEditor le;
InputView in( width-4 );
bool editing = true, update_stripes = true;
//mvhline( height-4, 1, ACS_HLINE, width-1 );
//mvprintw(height-4, width/2-9, "~<{ ||||||||| }>~" );
//mvhline( height-3, 1, ACS_HLINE, width-1 );
mvhline( height-3, 1, ' ', width-1 );
//mvaddch( height-3, 0, ACS_ULCORNER );
//mvaddch( height-3, 0, ACS_VLINE );
//mvaddch( height-3, width-1, ACS_URCORNER );
//mvaddch( height-3, width-1, ACS_VLINE );
//mvaddch( height-2, 0, ACS_VLINE );
//mvaddch( height-2, width-1, ACS_VLINE );
//mvhline( height-1, 1, ACS_HLINE, width-1 );
//mvaddch( height-1, 0, ACS_LLCORNER );
//mvaddch( height-1, width-1, ACS_LRCORNER );
//attroff( A_REVERSE );
//mvhline( 0, 1, ACS_HLINE, width-1 );
//mvprintw( 0, width/2-9, "~<{ calc-term }>~" );
//mvaddch( 0, 0, ACS_ULCORNER );
//mvaddch( 0, width-1, ACS_URCORNER );
//for( int i = 1; i < (height-4); ++i ) {
// mvaddch( i, 0, ACS_VLINE );
// mvaddch( i, width-1, ACS_VLINE );
//}
int const editor_pos_y = height-3;
int const editor_pos_x = 3;
mvhline( height-5, 1, ACS_HLINE, width-2 );
mvhline( height-1, 1, ACS_HLINE, width-2 );
//attroff( COLOR_PAIR( 1 ) );
//mvaddch( height-3, 1, '=' );
mvaddch( height-4, 1, ACS_VLINE );
mvaddch( height-2, 1, ACS_VLINE );
mvaddch( height-5, 1, ACS_ULCORNER );
mvaddch( height-1, 1, ACS_LLCORNER );
//mvaddch( height-4, width-1, ACS_URCORNER );
//mvprintw( height-5, width/2-8, " [ term~calc ] " );
mvprintw( height-5, width/2-6, " calc ~ term " );
mvaddch( editor_pos_y, 1, '>' );
//mvaddch( editor_pos_y, 2, '>' );
//mvaddch( height-4, width-1, ACS_LRCORNER );
move( editor_pos_y, editor_pos_x );
while( (ch = getch()) != (int)'q' )
{
char const* name = keyname( ch );
ASSERT( strlen( name ) > 0 )
bool ctrl = (name[0] == '^' && strlen( name ) > 1);
//mvprintw( 0, 0, "%x ", ch );
//mvprintw( 1, 0, "%s ", name );
//mvprintw( 2, 0, "%d ", width );
//ASSERT( (char)(ch & 0xff) != 'K' )
//if( ch == KEY_UP || (ctrl && name[1] == 'K') ) {
if( ch == KEY_UP || (!ctrl && ch == 'k') ) {
highlight += 1;
editing = false;
update_stripes = true;
}
//else if ( ch == KEY_DOWN || (ctrl && name[1] == 'J') ) {
else if ( ch == KEY_DOWN || (!ctrl && ch == 'j') ) {
highlight -= 1;
if( highlight < -1 )
highlight = -1;
if( highlight == -1 )
editing = true;
update_stripes = true;
}
else if( ctrl && name[1] == 'L' ) {
if( editing ) {
vs.clear();
update_stripes = true;
}
}
else if( ch == '\n' || ch == '\r' || ch == '\\' ) {
if( editing ) {
bool approx = (ch == '\\');
std::string const& str = le.get_buffer();
if( !str.empty() ) {
CI_Result* res = CI_submit( str.c_str() );
if( res ) {
SCOPE_EXIT( CI_result_free( res ) )
auto output_grid = []( char* _one_line, char** _grid, int rows, bool left_right ) {
ASSERT( rows > 0 )
auto one_line = std::string( _one_line );
auto grid = std::vector<std::string>();
auto length_0 = strlen( _grid[0] );
for( int j = 0; j < rows; j++ ) {
ASSERT( strlen( _grid[j] ) == length_0 )
grid.push_back( std::string( _grid[j] ) );
}
Stripe s({ {one_line, grid}, left_right, rows, (int)length_0 });
vs.push_back( s );
};
output_grid( res->input.one_line, res->input.grid, res->input.grid_rows, true );
if( approx && res->num_outputs > 1 ) {
output_grid( res->outputs[1].one_line, res->outputs[1].grid, res->outputs[1].grid_rows, false );
} else if( res->num_outputs > 0 ) {
output_grid( res->outputs[0].one_line, res->outputs[0].grid, res->outputs[0].grid_rows, false );
}
le = LineEditor();
update_stripes = true;
}
}
}
else {
std::string to_insert = vs[vs.size() - highlight - 1].e.one_line;
for( auto c : to_insert )
le.input( false, false, int( c ), NULL );
highlight = -1;
editing = true;
update_stripes = true;
}
}
else {
if( editing ) {
auto ki_old( le );
le.input( ctrl, false, ch, name );
if( le.get_buffer() == ki_old.get_buffer() &&
le.get_pos() == ki_old.get_pos() )
beep(); // can also use flash()
}
}
if( update_stripes ) {
draw_stripes( highlight, vs );
update_stripes = false;
}
mvaddnstr( editor_pos_y, editor_pos_x, in.render( le.get_pos(), le.get_buffer() ).c_str(), in.width );
if( editing ) {
curs_set(1);
move( editor_pos_y, editor_pos_x+in.rel_pos( le.get_pos() ) );
}
else {
curs_set(0);
}
refresh();
}
return 0;
}
int main( int argc, char* argv[] )
{
try {
return _main(argc, argv);
} catch( std::exception const& e ) {
std::cerr << "exception:" << e.what() << std::endl;
return 1;
}
}
<commit_msg>Some more tweaking of console interface<commit_after>//// Fancy ncurses terminal for calculators
//// Author: David P. Sicilia, June 2016
#include <ncurses.h>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <string.h>
#include <dlfcn.h>
#include <stdlib.h>
#include "assert.hpp"
#include "scope_exit.hpp"
#include "line_editor.hpp"
#include "input_view.hpp"
#include "icalcterm/icalcterm.h"
using namespace std;
struct Entry
{
std::string one_line;
std::vector<std::string> grid;
};
struct Stripe
{
Entry e;
bool is_left;
int y;
int x;
};
auto render_stripe( int width, Stripe const& s ) -> std::vector<std::string>
{
ASSERT( s.x >= 0 )
ASSERT( s.y >= 0 )
auto out = std::vector<std::string>( s.y );
//auto out = std::vector<std::string>( s.y+2 );
int start_x = s.is_left ? 1 : width-1-s.x;
ASSERT( start_x >= 0 )
auto pad = std::string( " " ); //start_x, ' ' );
ASSERT( width-start_x-s.x >= 0 )
auto end_pad = std::string( " " ); //width-start_x-s.x, ' ' );
for( int i = 0; i < s.y; ++i )
out[i] = pad + s.e.grid[i] + end_pad;
//out[i+1] = pad + s.e.grid[i] + end_pad;
//out[0] = pad + std::string( s.x, ' ' ) + end_pad;
//out[s.y+1] = pad + std::string( s.x, ' ' ) + end_pad;
return out;
}
auto draw_stripe( int width, int start_y, bool highlight, Stripe const& s ) -> void
{
auto text = render_stripe( width, s );
//if( highlight ) attroff( A_REVERSE );
if( highlight ) attron( A_REVERSE );
for( int i = text.size(); i > 0; --i ) {
if( start_y-i < 0 )
break;
ASSERT( start_y-int(text.size())+i >= 0 )
if( s.is_left )
mvprintw( start_y-text.size()+i, 1, text[i-1].c_str() );
else
mvprintw( start_y-text.size()+i, width-s.x-1, text[i-1].c_str() );
}
//if( highlight ) attron( A_REVERSE );
if( highlight ) attroff( A_REVERSE );
}
auto draw_stripes( int highlight, std::vector<Stripe> const& v ) -> void
{
int height = 0, width = 0;
getmaxyx( stdscr, height, width );
width -= 2;
(void)height;
int start_y = height-6;
ASSERT( start_y >= 0 )
int highlight_j = v.size() - highlight;
ASSERT( highlight_j >= 0 )
//for( int j = start_y; j >= 0; --j )
for( int j = start_y; j >= 1; --j )
mvhline( j, 1, ' ', width );
for( int j = v.size(); j > 0; --j ) {
if( start_y < 0 )
break;
Stripe const& s = v[j-1];
bool highlight = (j == highlight_j);
draw_stripe( width, start_y, highlight, s );
//start_y -= (s.y+2);
start_y -= (s.y);
}
}
std::vector<Stripe> vs = { };
#define GET_FUNC_SYM( sym ) \
sym ## _t sym; \
*(void**)(&sym) = dlsym( calc, #sym ); \
char const* STRING_JOIN( error__, __LINE__ ) = dlerror(); \
if( STRING_JOIN( error__, __LINE__) ) { \
fprintf( stderr, "%s\n", STRING_JOIN( error__, __LINE__) ); \
return 1; \
}
#ifdef OS_LINUX
char const* deflibname = "libdefcalc.so";
#else
#ifdef OS_OSX
char const* deflibname = "libdefcalc.dylib";
#endif
#endif
int _main(int argc, char* argv[])
{
char const* libname;
if( argc == 1 )
libname = deflibname;
else
libname = argv[1];
//printf("Loading library: %s\n", libname);
void* calc = dlopen( libname, RTLD_NOW );
if( !calc ) {
fprintf( stderr, "Unable to load library %s:\n%s\n", libname, dlerror() );
return 1;
}
SCOPE_EXIT( dlclose( calc ) )
GET_FUNC_SYM( CI_init )
GET_FUNC_SYM( CI_config )
GET_FUNC_SYM( CI_submit )
GET_FUNC_SYM( CI_result_free )
CI_init( NULL );
initscr();
SCOPE_EXIT( endwin() )
raw();
nonl();
noecho();
keypad(stdscr, TRUE);
int ch;
int highlight = -1;
int height = 0, width = 0;
getmaxyx( stdscr, height, width );
//attron( A_REVERSE );
for( int i = 0; i < height; ++i )
mvhline( i, 0, ' ', width );
draw_stripes( -1, vs );
LineEditor le;
InputView in( width-4 );
bool editing = true, update_stripes = true;
//mvhline( height-4, 1, ACS_HLINE, width-1 );
//mvprintw(height-4, width/2-9, "~<{ ||||||||| }>~" );
//mvhline( height-3, 1, ACS_HLINE, width-1 );
mvhline( height-3, 1, ' ', width-1 );
//mvaddch( height-3, 0, ACS_ULCORNER );
//mvaddch( height-3, 0, ACS_VLINE );
//mvaddch( height-3, width-1, ACS_URCORNER );
//mvaddch( height-3, width-1, ACS_VLINE );
//mvaddch( height-2, 0, ACS_VLINE );
//mvaddch( height-2, width-1, ACS_VLINE );
//mvhline( height-1, 1, ACS_HLINE, width-1 );
//mvaddch( height-1, 0, ACS_LLCORNER );
//mvaddch( height-1, width-1, ACS_LRCORNER );
//attroff( A_REVERSE );
//mvhline( 0, 1, ACS_HLINE, width-1 );
//mvprintw( 0, width/2-9, "~<{ calc-term }>~" );
//mvaddch( 0, 0, ACS_ULCORNER );
//mvaddch( 0, width-1, ACS_URCORNER );
//for( int i = 1; i < (height-4); ++i ) {
// mvaddch( i, 0, ACS_VLINE );
// mvaddch( i, width-1, ACS_VLINE );
//}
int const editor_pos_y = height-3;
int const editor_pos_x = 3;
mvhline( height-5, 2, ACS_HLINE, width-3 );
mvhline( height-1, 2, ACS_HLINE, width-4 );
//attroff( COLOR_PAIR( 1 ) );
//mvaddch( height-3, 1, '=' );
//mvaddch( height-4, 1, ACS_VLINE );
//mvaddch( height-2, 1, ACS_VLINE );
mvaddch( height-5, 1, ACS_ULCORNER );
mvaddch( height-1, 1, ACS_LLCORNER );
mvaddch( height-5, width-2, ACS_URCORNER );
mvaddch( height-1, width-2, ACS_LRCORNER );
//mvprintw( height-5, width/2-8, " [ term~calc ] " );
mvprintw( height-5, width/2-6, " calc ~ term " );
//mvaddch( editor_pos_y, 1, '>' );
//mvaddch( editor_pos_y, 2, '>' );
//mvaddch( height-4, width-1, ACS_LRCORNER );
move( editor_pos_y, editor_pos_x );
while( (ch = getch()) != (int)'q' )
{
char const* name = keyname( ch );
ASSERT( strlen( name ) > 0 )
bool ctrl = (name[0] == '^' && strlen( name ) > 1);
//mvprintw( 0, 0, "%x ", ch );
//mvprintw( 1, 0, "%s ", name );
//mvprintw( 2, 0, "%d ", width );
//ASSERT( (char)(ch & 0xff) != 'K' )
//if( ch == KEY_UP || (ctrl && name[1] == 'K') ) {
if( ch == KEY_UP || (!ctrl && ch == 'k') ) {
highlight += 1;
editing = false;
update_stripes = true;
}
//else if ( ch == KEY_DOWN || (ctrl && name[1] == 'J') ) {
else if ( ch == KEY_DOWN || (!ctrl && ch == 'j') ) {
highlight -= 1;
if( highlight < -1 )
highlight = -1;
if( highlight == -1 )
editing = true;
update_stripes = true;
}
else if( ctrl && name[1] == 'L' ) {
if( editing ) {
vs.clear();
update_stripes = true;
}
}
else if( ch == '\n' || ch == '\r' || ch == '\\' ) {
if( editing ) {
bool approx = (ch == '\\');
std::string const& str = le.get_buffer();
if( !str.empty() ) {
CI_Result* res = CI_submit( str.c_str() );
if( res ) {
SCOPE_EXIT( CI_result_free( res ) )
auto output_grid = []( char* _one_line, char** _grid, int rows, bool left_right ) {
ASSERT( rows > 0 )
auto one_line = std::string( _one_line );
auto grid = std::vector<std::string>();
auto length_0 = strlen( _grid[0] );
for( int j = 0; j < rows; j++ ) {
ASSERT( strlen( _grid[j] ) == length_0 )
grid.push_back( std::string( _grid[j] ) );
}
Stripe s({ {one_line, grid}, left_right, rows, (int)length_0 });
vs.push_back( s );
};
output_grid( res->input.one_line, res->input.grid, res->input.grid_rows, true );
if( approx && res->num_outputs > 1 ) {
output_grid( res->outputs[1].one_line, res->outputs[1].grid, res->outputs[1].grid_rows, false );
} else if( res->num_outputs > 0 ) {
output_grid( res->outputs[0].one_line, res->outputs[0].grid, res->outputs[0].grid_rows, false );
}
le = LineEditor();
update_stripes = true;
}
}
}
else {
std::string to_insert = vs[vs.size() - highlight - 1].e.one_line;
for( auto c : to_insert )
le.input( false, false, int( c ), NULL );
highlight = -1;
editing = true;
update_stripes = true;
}
}
else {
if( editing ) {
auto ki_old( le );
le.input( ctrl, false, ch, name );
if( le.get_buffer() == ki_old.get_buffer() &&
le.get_pos() == ki_old.get_pos() )
beep(); // can also use flash()
}
}
if( update_stripes ) {
draw_stripes( highlight, vs );
update_stripes = false;
}
mvaddnstr( editor_pos_y, editor_pos_x, in.render( le.get_pos(), le.get_buffer() ).c_str(), in.width );
if( editing ) {
curs_set(1);
move( editor_pos_y, editor_pos_x+in.rel_pos( le.get_pos() ) );
}
else {
curs_set(0);
}
refresh();
}
return 0;
}
int main( int argc, char* argv[] )
{
try {
return _main(argc, argv);
} catch( std::exception const& e ) {
std::cerr << "exception:" << e.what() << std::endl;
return 1;
}
}
<|endoftext|>
|
<commit_before>#ifndef MBGL_UTIL_VEC
#define MBGL_UTIL_VEC
#include <limits>
#include <type_traits>
#include <cmath>
#include <cstdint>
#include <array>
namespace MonkVG {
template <typename T = double>
struct vec2 {
struct null {};
typedef T Type;
T x, y;
inline vec2() {}
template<typename U = T, typename std::enable_if<std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline vec2(null) : x(std::numeric_limits<T>::quiet_NaN()), y(std::numeric_limits<T>::quiet_NaN()) {}
template<typename U = T, typename std::enable_if<!std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline vec2(null) : x(std::numeric_limits<T>::min()), y(std::numeric_limits<T>::min()) {}
inline vec2(const vec2& o) : x(o.x), y(o.y) {}
template<typename U>
inline vec2(const U& u) : x(u.x), y(u.y) {}
inline vec2(T x_, T y_) : x(x_), y(y_) {}
inline bool operator==(const vec2& rhs) const {
return x == rhs.x && y == rhs.y;
}
template <typename O>
inline typename std::enable_if<std::is_arithmetic<O>::value, vec2>::type
operator*(O o) const {
return {x * o, y * o};
}
template <typename O>
inline typename std::enable_if<std::is_arithmetic<O>::value, vec2>::type &
operator*=(O o) {
x *= o;
y *= o;
}
inline vec2<T> operator *(const std::array<float, 16>& matrix) {
return { x * matrix[0] + y * matrix[4] + matrix[12], x * matrix[1] + y * matrix[5] + matrix[13] };
}
template <typename O>
inline typename std::enable_if<std::is_arithmetic<O>::value, vec2>::type
operator-(O o) const {
return {x - o, y - o};
}
template <typename O>
inline typename std::enable_if<!std::is_arithmetic<O>::value, vec2>::type
operator-(const O &o) const {
return vec2<T>(x - o.x, y - o.y);
}
template <typename O>
inline typename std::enable_if<!std::is_arithmetic<O>::value, vec2>::type
operator+(const O &o) const {
return vec2<T>(x + o.x, y + o.y);
}
template <typename M>
inline vec2 matMul(const M &m) const {
return {m[0] * x + m[1] * y, m[2] * x + m[3] * y};
}
template<typename U = T, typename std::enable_if<std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline operator bool() const {
return !std::isnan(x) && !std::isnan(y);
}
template<typename U = T, typename std::enable_if<!std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline operator bool() const {
return x != std::numeric_limits<T>::min() && y != std::numeric_limits<T>::min();
}
};
template <typename T = double>
struct vec3 {
T x, y, z;
inline vec3() {}
inline vec3(const vec3& o) : x(o.x), y(o.y), z(o.z) {}
inline vec3(T x_, T y_, T z_) : x(x_), y(y_), z(z_) {}
inline bool operator==(const vec3& rhs) const {
return x == rhs.x && y == rhs.y && z == rhs.z;
}
};
typedef vec2<int16_t> Coordinate;
}
#endif
<commit_msg>Added mapbox-gl copyright<commit_after>/*
mapbox-gl-native copyright (c) 2014-2016 Mapbox.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MBGL_UTIL_VEC
#define MBGL_UTIL_VEC
#include <limits>
#include <type_traits>
#include <cmath>
#include <cstdint>
#include <array>
namespace MonkVG {
template <typename T = double>
struct vec2 {
struct null {};
typedef T Type;
T x, y;
inline vec2() {}
template<typename U = T, typename std::enable_if<std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline vec2(null) : x(std::numeric_limits<T>::quiet_NaN()), y(std::numeric_limits<T>::quiet_NaN()) {}
template<typename U = T, typename std::enable_if<!std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline vec2(null) : x(std::numeric_limits<T>::min()), y(std::numeric_limits<T>::min()) {}
inline vec2(const vec2& o) : x(o.x), y(o.y) {}
template<typename U>
inline vec2(const U& u) : x(u.x), y(u.y) {}
inline vec2(T x_, T y_) : x(x_), y(y_) {}
inline bool operator==(const vec2& rhs) const {
return x == rhs.x && y == rhs.y;
}
template <typename O>
inline typename std::enable_if<std::is_arithmetic<O>::value, vec2>::type
operator*(O o) const {
return {x * o, y * o};
}
template <typename O>
inline typename std::enable_if<std::is_arithmetic<O>::value, vec2>::type &
operator*=(O o) {
x *= o;
y *= o;
}
inline vec2<T> operator *(const std::array<float, 16>& matrix) {
return { x * matrix[0] + y * matrix[4] + matrix[12], x * matrix[1] + y * matrix[5] + matrix[13] };
}
template <typename O>
inline typename std::enable_if<std::is_arithmetic<O>::value, vec2>::type
operator-(O o) const {
return {x - o, y - o};
}
template <typename O>
inline typename std::enable_if<!std::is_arithmetic<O>::value, vec2>::type
operator-(const O &o) const {
return vec2<T>(x - o.x, y - o.y);
}
template <typename O>
inline typename std::enable_if<!std::is_arithmetic<O>::value, vec2>::type
operator+(const O &o) const {
return vec2<T>(x + o.x, y + o.y);
}
template <typename M>
inline vec2 matMul(const M &m) const {
return {m[0] * x + m[1] * y, m[2] * x + m[3] * y};
}
template<typename U = T, typename std::enable_if<std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline operator bool() const {
return !std::isnan(x) && !std::isnan(y);
}
template<typename U = T, typename std::enable_if<!std::numeric_limits<U>::has_quiet_NaN, int>::type = 0>
inline operator bool() const {
return x != std::numeric_limits<T>::min() && y != std::numeric_limits<T>::min();
}
};
template <typename T = double>
struct vec3 {
T x, y, z;
inline vec3() {}
inline vec3(const vec3& o) : x(o.x), y(o.y), z(o.z) {}
inline vec3(T x_, T y_, T z_) : x(x_), y(y_), z(z_) {}
inline bool operator==(const vec3& rhs) const {
return x == rhs.x && y == rhs.y && z == rhs.z;
}
};
typedef vec2<int16_t> Coordinate;
}
#endif
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file BlockQueue.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include "BlockQueue.h"
#include <libdevcore/Log.h>
#include <libethcore/Exceptions.h>
#include <libethcore/BlockInfo.h>
#include "BlockChain.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
ImportResult BlockQueue::import(bytesConstRef _block, BlockChain const& _bc, bool _isOurs)
{
// Check if we already know this block.
h256 h = BlockInfo::headerHash(_block);
cblockq << "Queuing block" << h.abridged() << "for import...";
UpgradableGuard l(m_lock);
if (m_readySet.count(h) || m_drainingSet.count(h) || m_unknownSet.count(h) || m_knownBad.count(h))
{
// Already know about this one.
cblockq << "Already known.";
return ImportResult::AlreadyKnown;
}
// VERIFY: populates from the block and checks the block is internally coherent.
BlockInfo bi;
try
{
// TODO: quick verify
bi.populate(_block);
bi.verifyInternals(_block);
}
catch (Exception const& _e)
{
cwarn << "Ignoring malformed block: " << diagnostic_information(_e);
return ImportResult::Malformed;
}
// Check block doesn't already exist first!
if (_bc.details(h))
{
cblockq << "Already known in chain.";
return ImportResult::AlreadyInChain;
}
UpgradeGuard ul(l);
// Check it's not in the future
(void)_isOurs;
if (bi.timestamp > (u256)time(0)/* && !_isOurs*/)
{
m_future.insert(make_pair((unsigned)bi.timestamp, _block.toBytes()));
char buf[24];
time_t bit = (unsigned)bi.timestamp;
if (strftime(buf, 24, "%X", localtime(&bit)) == 0)
buf[0] = '\0'; // empty if case strftime fails
cblockq << "OK - queued for future [" << bi.timestamp << "vs" << time(0) << "] - will wait until" << buf;
return ImportResult::FutureTime;
}
else
{
// We now know it.
if (m_knownBad.count(bi.parentHash))
{
m_knownBad.insert(bi.hash());
// bad parent; this is bad too, note it as such
return ImportResult::BadChain;
}
else if (!m_readySet.count(bi.parentHash) && !m_drainingSet.count(bi.parentHash) && !_bc.isKnown(bi.parentHash))
{
// We don't know the parent (yet) - queue it up for later. It'll get resent to us if we find out about its ancestry later on.
cblockq << "OK - queued as unknown parent:" << bi.parentHash.abridged();
m_unknown.insert(make_pair(bi.parentHash, make_pair(h, _block.toBytes())));
m_unknownSet.insert(h);
return ImportResult::UnknownParent;
}
else
{
// If valid, append to blocks.
cblockq << "OK - ready for chain insertion.";
m_ready.push_back(_block.toBytes());
m_readySet.insert(h);
noteReadyWithoutWriteGuard(h);
m_onReady();
return ImportResult::Success;
}
}
}
bool BlockQueue::doneDrain(h256s const& _bad)
{
WriteGuard l(m_lock);
m_drainingSet.clear();
if (_bad.size())
{
vector<bytes> old;
swap(m_ready, old);
for (auto& b: old)
{
BlockInfo bi(b);
if (m_knownBad.count(bi.parentHash))
m_knownBad.insert(bi.hash());
else
m_ready.push_back(std::move(b));
}
}
m_knownBad += _bad;
return !m_readySet.empty();
}
void BlockQueue::tick(BlockChain const& _bc)
{
UpgradableGuard l(m_lock);
if (m_future.empty())
return;
cblockq << "Checking past-future blocks...";
unsigned t = time(0);
if (t <= m_future.begin()->first)
return;
cblockq << "Past-future blocks ready.";
vector<bytes> todo;
{
UpgradeGuard l2(l);
auto end = m_future.lower_bound(t);
for (auto i = m_future.begin(); i != end; ++i)
todo.push_back(move(i->second));
m_future.erase(m_future.begin(), end);
}
cblockq << "Importing" << todo.size() << "past-future blocks.";
for (auto const& b: todo)
import(&b, _bc);
}
template <class T> T advanced(T _t, unsigned _n)
{
std::advance(_t, _n);
return _t;
}
QueueStatus BlockQueue::blockStatus(h256 const& _h) const
{
ReadGuard l(m_lock);
return
m_readySet.count(_h) ?
QueueStatus::Ready :
m_drainingSet.count(_h) ?
QueueStatus::Importing :
m_unknownSet.count(_h) ?
QueueStatus::UnknownParent :
m_knownBad.count(_h) ?
QueueStatus::Bad :
QueueStatus::Unknown;
}
void BlockQueue::drain(std::vector<bytes>& o_out, unsigned _max)
{
WriteGuard l(m_lock);
if (m_drainingSet.empty())
{
o_out.resize(min<unsigned>(_max, m_ready.size()));
for (unsigned i = 0; i < o_out.size(); ++i)
swap(o_out[i], m_ready[i]);
m_ready.erase(m_ready.begin(), advanced(m_ready.begin(), o_out.size()));
for (auto const& bs: o_out)
{
auto h = sha3(bs);
m_drainingSet.insert(h);
m_readySet.erase(h);
}
// swap(o_out, m_ready);
// swap(m_drainingSet, m_readySet);
}
}
void BlockQueue::noteReadyWithoutWriteGuard(h256 _good)
{
list<h256> goodQueue(1, _good);
while (!goodQueue.empty())
{
auto r = m_unknown.equal_range(goodQueue.front());
goodQueue.pop_front();
for (auto it = r.first; it != r.second; ++it)
{
m_ready.push_back(it->second.second);
auto newReady = it->second.first;
m_unknownSet.erase(newReady);
m_readySet.insert(newReady);
goodQueue.push_back(newReady);
}
m_unknown.erase(r.first, r.second);
}
}
void BlockQueue::retryAllUnknown()
{
for (auto it = m_unknown.begin(); it != m_unknown.end(); ++it)
{
m_ready.push_back(it->second.second);
auto newReady = it->second.first;
m_unknownSet.erase(newReady);
m_readySet.insert(newReady);
}
m_unknown.clear();
}
<commit_msg>Avoid deadlock when have past future blocks.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file BlockQueue.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include "BlockQueue.h"
#include <libdevcore/Log.h>
#include <libethcore/Exceptions.h>
#include <libethcore/BlockInfo.h>
#include "BlockChain.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
ImportResult BlockQueue::import(bytesConstRef _block, BlockChain const& _bc, bool _isOurs)
{
// Check if we already know this block.
h256 h = BlockInfo::headerHash(_block);
cblockq << "Queuing block" << h.abridged() << "for import...";
UpgradableGuard l(m_lock);
if (m_readySet.count(h) || m_drainingSet.count(h) || m_unknownSet.count(h) || m_knownBad.count(h))
{
// Already know about this one.
cblockq << "Already known.";
return ImportResult::AlreadyKnown;
}
// VERIFY: populates from the block and checks the block is internally coherent.
BlockInfo bi;
try
{
// TODO: quick verify
bi.populate(_block);
bi.verifyInternals(_block);
}
catch (Exception const& _e)
{
cwarn << "Ignoring malformed block: " << diagnostic_information(_e);
return ImportResult::Malformed;
}
// Check block doesn't already exist first!
if (_bc.details(h))
{
cblockq << "Already known in chain.";
return ImportResult::AlreadyInChain;
}
UpgradeGuard ul(l);
// Check it's not in the future
(void)_isOurs;
if (bi.timestamp > (u256)time(0)/* && !_isOurs*/)
{
m_future.insert(make_pair((unsigned)bi.timestamp, _block.toBytes()));
char buf[24];
time_t bit = (unsigned)bi.timestamp;
if (strftime(buf, 24, "%X", localtime(&bit)) == 0)
buf[0] = '\0'; // empty if case strftime fails
cblockq << "OK - queued for future [" << bi.timestamp << "vs" << time(0) << "] - will wait until" << buf;
return ImportResult::FutureTime;
}
else
{
// We now know it.
if (m_knownBad.count(bi.parentHash))
{
m_knownBad.insert(bi.hash());
// bad parent; this is bad too, note it as such
return ImportResult::BadChain;
}
else if (!m_readySet.count(bi.parentHash) && !m_drainingSet.count(bi.parentHash) && !_bc.isKnown(bi.parentHash))
{
// We don't know the parent (yet) - queue it up for later. It'll get resent to us if we find out about its ancestry later on.
cblockq << "OK - queued as unknown parent:" << bi.parentHash.abridged();
m_unknown.insert(make_pair(bi.parentHash, make_pair(h, _block.toBytes())));
m_unknownSet.insert(h);
return ImportResult::UnknownParent;
}
else
{
// If valid, append to blocks.
cblockq << "OK - ready for chain insertion.";
m_ready.push_back(_block.toBytes());
m_readySet.insert(h);
noteReadyWithoutWriteGuard(h);
m_onReady();
return ImportResult::Success;
}
}
}
bool BlockQueue::doneDrain(h256s const& _bad)
{
WriteGuard l(m_lock);
m_drainingSet.clear();
if (_bad.size())
{
vector<bytes> old;
swap(m_ready, old);
for (auto& b: old)
{
BlockInfo bi(b);
if (m_knownBad.count(bi.parentHash))
m_knownBad.insert(bi.hash());
else
m_ready.push_back(std::move(b));
}
}
m_knownBad += _bad;
return !m_readySet.empty();
}
void BlockQueue::tick(BlockChain const& _bc)
{
vector<bytes> todo;
{
UpgradableGuard l(m_lock);
if (m_future.empty())
return;
cblockq << "Checking past-future blocks...";
unsigned t = time(0);
if (t <= m_future.begin()->first)
return;
cblockq << "Past-future blocks ready.";
{
UpgradeGuard l2(l);
auto end = m_future.lower_bound(t);
for (auto i = m_future.begin(); i != end; ++i)
todo.push_back(move(i->second));
m_future.erase(m_future.begin(), end);
}
}
cblockq << "Importing" << todo.size() << "past-future blocks.";
for (auto const& b: todo)
import(&b, _bc);
}
template <class T> T advanced(T _t, unsigned _n)
{
std::advance(_t, _n);
return _t;
}
QueueStatus BlockQueue::blockStatus(h256 const& _h) const
{
ReadGuard l(m_lock);
return
m_readySet.count(_h) ?
QueueStatus::Ready :
m_drainingSet.count(_h) ?
QueueStatus::Importing :
m_unknownSet.count(_h) ?
QueueStatus::UnknownParent :
m_knownBad.count(_h) ?
QueueStatus::Bad :
QueueStatus::Unknown;
}
void BlockQueue::drain(std::vector<bytes>& o_out, unsigned _max)
{
WriteGuard l(m_lock);
if (m_drainingSet.empty())
{
o_out.resize(min<unsigned>(_max, m_ready.size()));
for (unsigned i = 0; i < o_out.size(); ++i)
swap(o_out[i], m_ready[i]);
m_ready.erase(m_ready.begin(), advanced(m_ready.begin(), o_out.size()));
for (auto const& bs: o_out)
{
auto h = sha3(bs);
m_drainingSet.insert(h);
m_readySet.erase(h);
}
// swap(o_out, m_ready);
// swap(m_drainingSet, m_readySet);
}
}
void BlockQueue::noteReadyWithoutWriteGuard(h256 _good)
{
list<h256> goodQueue(1, _good);
while (!goodQueue.empty())
{
auto r = m_unknown.equal_range(goodQueue.front());
goodQueue.pop_front();
for (auto it = r.first; it != r.second; ++it)
{
m_ready.push_back(it->second.second);
auto newReady = it->second.first;
m_unknownSet.erase(newReady);
m_readySet.insert(newReady);
goodQueue.push_back(newReady);
}
m_unknown.erase(r.first, r.second);
}
}
void BlockQueue::retryAllUnknown()
{
for (auto it = m_unknown.begin(); it != m_unknown.end(); ++it)
{
m_ready.push_back(it->second.second);
auto newReady = it->second.first;
m_unknownSet.erase(newReady);
m_readySet.insert(newReady);
}
m_unknown.clear();
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <iostream>
#include <fstream>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <nwg.h>
#include <nwg_basicprotocolcodec.h>
#define BUFFSIZE SZ_64KB
#define READBUFFSIZE SZ_4MB
#ifndef SILENT
#define SILENT 1
#endif
#if SILENT
#define _printf(...)
#else
#define _printf(...) fprintf (stdout, __VA_ARGS__)
#endif
using boost::regex;
using boost::regex_match;
using boost::regex_replace;
using boost::smatch;
using namespace boost::filesystem;
static int numReq = 0;
static path workingPath;
struct SessionState {
int reqNo = 0;
size_t nwritten = 0;
size_t length = 0;
std::ifstream *is = nullptr;
bool readAndWriteFile = false;
};
#define STATE "STATE"
#define GETMSG(obj) dynamic_cast<Nwg::MessageBuffer &>(obj)
#define GETSTATE(session) session.get<SessionState>(STATE)
#define PATTERN "([a-zA-Z]+) (/[0-9a-zA-Z\\-_,.;:'\"\\[\\]\\(\\)+=!@#$%^&*<>/?~`{}|]*) (HTTP/\\d\\.\\d)(\r|)$"
class FtpHandler : public Nwg::Handler
{
private:
static boost::regex pattern;
std::string decodeUrl(const std::string &url)
{
std::string nurl = url;
static regex reSpace("%20");
nurl = regex_replace(nurl, reSpace, " ");
return nurl;
}
public:
void sessionOpened(Nwg::Session &session)
{
std::shared_ptr<SessionState> state(new SessionState());
state->reqNo = ++numReq;
session.put<SessionState>(STATE, state);
}
void messageReceived(Nwg::Session &session, Nwg::MessageBuffer &obj)
{
Nwg::MessageBuffer &msg = GETMSG(obj);
SessionState &state = GETSTATE(session);
if (session.stillReading) {
session.close();
}
std::shared_ptr<Nwg::MessageBuffer> out(new Nwg::MessageBuffer(BUFFSIZE));
std::string h1 = msg.sreadUntil('\n');
_printf("==== REQUEST RECEIVED %d ====\n", state.reqNo);
_printf("%s\n", h1.c_str());
smatch what;
std::string url = "";
bool requestOk = false;
if (regex_match(h1, what, pattern)) {
_printf("Method: %s\n", what[1].str().c_str());
_printf("URL: %s\n", what[2].str().c_str());
_printf("HTTP Version: %s\n", what[3].str().c_str());
url = decodeUrl(what[2].str());
requestOk = true;
} else {
_printf("MALFORMED REQUEST.\n");
}
_printf("==== ==== ====\n");
path urlPath = workingPath;
urlPath += url;
/* request is okay and it is a directory */
if (requestOk && is_directory(urlPath) && ((int) url.find("..") == -1))
{
std::string sout;
sout.reserve(BUFFSIZE);
path p = urlPath;
if (is_directory(p)) {
typedef std::vector<path> vec;
vec v;
std::copy(directory_iterator(p), directory_iterator(), std::back_inserter<vec>(v));
sort(v.begin(), v.end());
for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) {
if (is_directory(*it)) {
sout += " <li><a href=\"" + it->filename().string() + "/\">" + it->filename().string() + "/</li>\n";
} else {
sout += " <li><a href=\"" + it->filename().string() + "\">" + it->filename().string() + "</li>\n";
}
}
}
out->put("HTTP/1.1 200 OK\r\n");
out->put("Content-Type: text/html\r\n");
out->put("Connection: close\r\n");
out->put("\r\n");
out->put("<h1>Listing of " + urlPath.string() + "</h1>\n");
out->put("<ul>\n");
out->put(sout);
out->put("</ul>\n");
out->flip();
session.write(out);
return;
}
/* request is okay and it is likely a regular file */
else if (requestOk)
{
url = url.substr(1);
path p(url);
if (is_regular_file(p))
{
std::ifstream *is = new std::ifstream(p.string(), std::ios::binary);
is->seekg(0, is->end);
int length = is->tellg();
is->seekg(0, is->beg);
state.readAndWriteFile = true;
state.length = length;
state.nwritten = 0;
state.is = is;
_printf("==== DATA TO BE WRITTEN: %d ====\n", length);
out->put("HTTP/1.1 200 OK\r\n");
out->put("Content-Type: text/plain\r\n");
out->put("Connection: close\r\n");
out->put("Content-Length: " + std::to_string(length) + "\r\n");
out->put("\r\n");
out->flip();
/* send the header first */
/* will continue reading the file and sending it at messageSent() */
session.write(out);
return;
}
/* neither regular file nor directory, let's assume it is not found */
else
{
out->put("HTTP/1.1 404 NOT FOUND\r\n");
out->put("Content-Type: text/html\r\n");
out->put("Connection: close\r\n");
out->put("\r\n");
out->put("<h1>404 NOT FOUND</h1>\n");
out->put("<pre>" + url + "</pre>\n");
out->flip();
session.write(out);
return;
}
}
/* request is NOT okay */
else
{
out->put("HTTP/1.1 400 BAD REQUEST\r\n");
out->put("Content-Type: text/html\r\n");
out->put("Connection: close\r\n");
out->put("\r\n");
out->put("<h1>400 BAD REQUEST</h1>\n");
out->flip();
session.write(out);
return;
}
}
void messageSent(Nwg::Session &session, Nwg::MessageBuffer &obj)
{
Nwg::MessageBuffer &msg = GETMSG(obj);
SessionState &state = GETSTATE(session);
if (state.readAndWriteFile && state.nwritten < state.length)
{
/* continue reading file and sending it chunk by chunk @READBUFFSIZE */
std::shared_ptr<Nwg::MessageBuffer> out(new Nwg::MessageBuffer(BUFFSIZE));
std::ifstream *is = state.is;
char *buff = new char[READBUFFSIZE];
is->read(buff, READBUFFSIZE);
out->put(buff, is->gcount());
out->flip();
delete [] buff;
state.nwritten += is->gcount();
session.write(out);
if (state.nwritten == state.length) {
state.is->close();
delete state.is;
state.is = nullptr;
state.readAndWriteFile = false;
state.length = 0;
state.nwritten = 0;
_printf("==== STREAM CLOSED ====\n");
}
}
/* there is nothing left to be written */
else
{
session.close();
_printf("==== DATA IS COMPLETELY SENT ====\n");
}
}
void sessionClosed(Nwg::Session &session)
{
SessionState &state = GETSTATE(session);
if (state.readAndWriteFile) {
state.is->close();
delete state.is;
state.is = nullptr;
_printf("==== STREAM CLOSED ====\n");
_printf("==== DATA IS NOT COMPLETELY SENT ====\n");
}
}
};
boost::regex FtpHandler::pattern = boost::regex(PATTERN);
void run(int port)
{
Nwg::EventLoop eventLoop;
Nwg::Acceptor acceptor(&eventLoop, port);
acceptor.setBuffSize(BUFFSIZE);
acceptor.setReadBuffSize(READBUFFSIZE);
acceptor.setProtocolCodec(std::make_shared<Nwg::BasicProtocolCodec>());
acceptor.setHandler(std::make_shared<FtpHandler>());
printf("Listening on port %d\n", acceptor.getPort());
printf("Open http://127.0.0.1:%d/\n", acceptor.getPort());
acceptor.listen();
eventLoop.dispatch();
}
int main(int argc, char **argv)
{
workingPath = absolute(current_path());
run([&]() -> int {
if (argc > 1) {
return std::stoi(argv[1]);
} else {
return 8821;
}
}());
return 0;
}
<commit_msg>Update examples/ftpserver.cc<commit_after>#include <cstdio>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <boost/regex.hpp>
#include <boost/filesystem.hpp>
#include <nwg.h>
#include <nwg_basicprotocolcodec.h>
#define BUFFSIZE SZ_64KB
#define READBUFFSIZE SZ_4MB
#ifndef SILENT
#define SILENT 1
#endif
#if SILENT
#define _printf(...)
#else
#define _printf(...) fprintf (stdout, __VA_ARGS__)
#endif
using boost::regex;
using boost::regex_match;
using boost::regex_replace;
using boost::smatch;
using namespace boost::filesystem;
static path workingPath;
static int numReq = 0;
static int initialDataPort = 37100;
const std::string R_WELCOME_MSG = "220 Nwg FTP Server Example\r\n";
const std::string R_SPECIFY_PASSWORD = "331 Please specify password.\r\n";
const std::string R_LOGIN_SUCCESSFUL = "230 Login successful.\r\n";
const std::string R_ENTER_PASV_ = "227 Entering Passive Mode ";
const std::string R_SHOW_PWD_ = "257 ";
const std::string R_OPENCONN_LIST = "150 Here comes the directory listing.\r\n";
const std::string R_OPENCONN_RETR = "150 Opening connection.\r\n";
const std::string R_TRF_COMPLETE = "226 Transfer complete.\r\n";
const std::string R_DIR_CHANGED = "250 Directory successfully changed.\r\n";
const std::string R_SYST = "215 UNIX Type: L8\r\n";
const std::string R_MUST_LOGIN = "530 You must login.\r\n";
const std::string R_UNKWN_COMMAND = "550 Unknown command.\r\n";
const std::string R_GOODBYE = "221 Goodbye.\r\n";
const std::string R_USE_PASV_FIRST = "425 Use PASV first.\r\n";
const std::string R_TYPE = "200 Switching to Binary mode.\r\n";
#define CMD_USER "USER"
#define CMD_PASS "PASS"
#define CMD_SYST "SYST"
#define CMD_PASV "PASV"
#define CMD_LIST "LIST"
#define CMD_NLST "NLST"
#define CMD_CWD "CWD"
#define CMD_PWD "PWD"
#define CMD_RETR "RETR"
#define CMD_QUIT "QUIT"
#define CMD_TYPE "TYPE"
std::vector<std::string> tokenize(const std::string &str)
{
std::string buf;
std::stringstream ss(str);
std::vector<std::string> tokens;
while (ss >> buf) {
tokens.push_back(buf);
}
return tokens;
}
std::string port12(int port)
{
std::stringstream ss;
ss << port / 256 << "," << port % 256;
return ss.str();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// Ftp Data Handler
////////////////////////////////////////////////////////////////////////////////////////////////////
class FtpDataHandler : public Nwg::Handler
{
struct State;
public:
void setState(State *state) { _state = state; }
void setCommand(const std::string &command) { _command = command; }
void setParameter(const std::string ¶meter) { _parameter = parameter; }
void setCurrentPath(const path ¤tPath) { _currentPath = currentPath; }
void sessionOpened(Nwg::Session &session)
{
std::shared_ptr<Nwg::MessageBuffer> out(new Nwg::MessageBuffer(BUFFSIZE));
out->put("");
out->flip();
session.write(out);
}
void messageReceived(Nwg::Session &session, Nwg::MessageBuffer &msg)
{
}
void messageSent(Nwg::Session &session, Nwg::MessageBuffer &msg)
{
std::shared_ptr<Nwg::MessageBuffer> out(new Nwg::MessageBuffer(BUFFSIZE));
if (closeNow) {
session.close();
_command = "";
closeNow = false;
}
if (_command == "") {
out->put("");
}
else {
// LIST
if (_command == CMD_LIST) {
std::stringstream ss;
path p = current_path() / _currentPath;
if (is_directory(p)) {
typedef std::vector<path> vec;
vec v;
std::copy(directory_iterator(p), directory_iterator(), std::back_inserter<vec>(v));
sort(v.begin(), v.end());
for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) {
if (is_directory(*it)) {
ss << "drwxrwxr-x 2 1000 1000 " << std::setw(10) << 4096 << " Aug 01 18:00 " << it->filename().string() << "\r\n";
} else {
ss << "-rw-rw-r-- 1 1000 1000 " << std::setw(10) << file_size(_currentPath / it->filename()) << " Aug 01 18:00 " << it->filename().string() << "\r\n";
}
}
}
out->put(ss.str());
closeNow = true;
}
// RETR
else if (_command == CMD_RETR) {
std::ifstream is((_currentPath.string() != "" ? _currentPath.string() + "/" : "") + _parameter, std::ios::binary);
std::string content;
is.seekg(0, std::ios::end);
content.reserve(is.tellg());
is.seekg(0, std::ios::beg);
content.assign((std::istreambuf_iterator<char>(is)),
std::istreambuf_iterator<char>());
out->put(content);
closeNow = true;
}
else {
out->put("Unknown command.\r\n");
closeNow = true;
}
}
out->flip();
session.write(out);
}
void sessionClosed(Nwg::Session &session)
{
}
private:
State *_state;
path _currentPath;
std::string _command = "";
std::string _parameter = "";
bool closeNow = false;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// Ftp Command Handler
////////////////////////////////////////////////////////////////////////////////////////////////////
struct State
{
int reqNo = -1;
bool loggedIn = false;
bool quit = false;
bool pasvMode = false;
int pasvPort = -1;
path absolutePath;
path relativePath;
std::string lastCommand = "";
std::string lastParameter = "";
Nwg::Acceptor *dataHandlerAcceptor = NULL;
std::shared_ptr<FtpDataHandler> dataHandler;
};
class FtpCommandHandler : public Nwg::Handler
{
public:
void sessionOpened(Nwg::Session &session)
{
std::shared_ptr<Nwg::MessageBuffer> out(new Nwg::MessageBuffer(BUFFSIZE));
std::shared_ptr<State> state(new State());
state->reqNo = ++numReq;
state->absolutePath = workingPath;
state->relativePath = "";
session.put<State>("state", state);
printf("Session opened #%d\n", state->reqNo);
out->put(R_WELCOME_MSG);
out->flip();
session.write(out);
}
void messageReceived(Nwg::Session &session, Nwg::MessageBuffer &msg)
{
std::shared_ptr<Nwg::MessageBuffer> out(new Nwg::MessageBuffer(BUFFSIZE));
State &state = session.get<State>("state");
std::vector<std::string> tokens = tokenize(msg.sreadUntil('\n'));
std::string &command = tokens[0];
printf("Command: %s\n", command.c_str());
// Not logged in
if (!state.loggedIn && command != CMD_QUIT) {
if (state.lastCommand == CMD_USER) {
if (command == CMD_PASS) {
state.loggedIn = true;
out->put(R_LOGIN_SUCCESSFUL);
} else {
out->put(R_UNKWN_COMMAND);
}
} else {
if (command == CMD_USER) {
state.lastCommand = CMD_USER;
out->put(R_SPECIFY_PASSWORD);
} else {
out->put(R_MUST_LOGIN);
}
}
goto end;
}
// PASV
if (command == CMD_PASV) {
state.pasvMode = true;
if (state.pasvPort == -1) {
state.pasvPort = initialDataPort++;
}
std::stringstream ss;
ss << R_ENTER_PASV_ << "(127,0,0,1," << port12(state.pasvPort) << ")\r\n";
out->put(ss.str());
if (state.dataHandlerAcceptor == NULL) {
state.dataHandler = std::make_shared<FtpDataHandler>();
state.dataHandlerAcceptor = new Nwg::Acceptor(session.getService().getEventLoop(), state.pasvPort);
state.dataHandlerAcceptor->setBuffSize(BUFFSIZE);
state.dataHandlerAcceptor->setHandler(state.dataHandler);
state.dataHandlerAcceptor->listen();
}
}
// TYPE
else if (command == CMD_TYPE) {
out->put(R_TYPE);
}
// SYST
else if (command == CMD_SYST) {
out->put(R_SYST);
}
// CWD
else if (command == CMD_CWD) {
std::string npath = tokens[1];
if (npath == ".." || npath == "../") {
state.relativePath.remove_leaf();
} else {
state.relativePath /= path(npath);
}
out->put(R_DIR_CHANGED);
}
// PWD
else if (command == CMD_PWD) {
std::stringstream ss;
ss << R_SHOW_PWD_ << "\"/" << state.relativePath.string() << "\"\r\n";
out->put(ss.str());
}
// LIST
else if (command == CMD_LIST) {
if (!state.pasvMode) {
out->put(R_USE_PASV_FIRST);
} else {
state.dataHandler->setCommand(CMD_LIST);
state.dataHandler->setCurrentPath(state.relativePath);
state.lastCommand = CMD_LIST;
out->put(R_OPENCONN_LIST);
out->put(R_TRF_COMPLETE);
state.pasvMode = false;
}
}
// RETR
else if (command == CMD_RETR) {
if (!state.pasvMode) {
out->put(R_USE_PASV_FIRST);
} else {
state.dataHandler->setCommand(CMD_RETR);
state.dataHandler->setParameter(tokens[1]);
state.lastCommand = CMD_RETR;
out->put(R_OPENCONN_RETR);
out->put(R_TRF_COMPLETE);
state.pasvMode = false;
}
}
// QUIT
else if (command == CMD_QUIT) {
out->put(R_GOODBYE);
state.quit = true;
}
// Unknown Command
else {
printf("GOT YA! %s\n", command.c_str());
out->put(R_UNKWN_COMMAND);
}
end:
out->flip();
session.write(out);
}
void messageSent(Nwg::Session &session, Nwg::MessageBuffer &msg)
{
State &state = session.get<State>("state");
if (state.quit) {
session.close();
delete state.dataHandlerAcceptor;
}
}
void sessionClosed(Nwg::Session &session)
{
State &state = session.get<State>("state");
printf("Session closed #%d\n", state.reqNo);
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// Main
////////////////////////////////////////////////////////////////////////////////////////////////////
void run(int port)
{
Nwg::EventLoop eventLoop;
Nwg::Acceptor acceptor(&eventLoop, port);
acceptor.setBuffSize(BUFFSIZE);
acceptor.setReadBuffSize(READBUFFSIZE);
acceptor.setProtocolCodec(std::make_shared<Nwg::BasicProtocolCodec>());
acceptor.setHandler(std::make_shared<FtpCommandHandler>());
printf("Listening on port %d\n", acceptor.getPort());
acceptor.listen();
eventLoop.dispatch();
}
int main(int argc, char **argv)
{
workingPath = absolute(current_path());
run([&]() -> int {
if (argc > 1) {
return std::stoi(argv[1]);
} else {
return 8821;
}
}());
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2020 The Android Open Source Project
*
* 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 <android/native_window_jni.h>
#include <cassert>
extern "C" {
JNIEXPORT jint JNICALL
Java_androidx_camera_testing_SurfaceFormatUtil_nativeGetSurfaceFormat(JNIEnv *env, jclass clazz,
jobject jsurface) {
ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, jsurface);
assert(nativeWindow != nullptr);
return ANativeWindow_getFormat(nativeWindow);
}
} // extern "C"
<commit_msg>Release ANativeWindow to avoid leak after obtaining surface format.<commit_after>/*
* Copyright 2020 The Android Open Source Project
*
* 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 <android/native_window_jni.h>
#include <cassert>
extern "C" {
JNIEXPORT jint JNICALL
Java_androidx_camera_testing_SurfaceFormatUtil_nativeGetSurfaceFormat(JNIEnv *env, jclass clazz,
jobject jsurface) {
ANativeWindow *nativeWindow = ANativeWindow_fromSurface(env, jsurface);
assert(nativeWindow != nullptr);
int32_t format = ANativeWindow_getFormat(nativeWindow);
ANativeWindow_release(nativeWindow);
return format;
}
} // extern "C"
<|endoftext|>
|
<commit_before>#pragma once
#include "CGameProjectile.hpp"
#include "Camera/CCameraShakeData.hpp"
namespace urde {
class CEnergyProjectile : public CGameProjectile {
CSfxHandle x2e8_sfx;
zeus::CVector3f x2ec_dir;
float x2f8_mag;
CCameraShakeData x2fc_camShake;
bool x3d0_24_dead : 1;
bool x3d0_25_ : 1;
bool x3d0_26_ : 1;
bool x3d0_27_camShakeDirty : 1;
float x3d4_curTime = 0.f;
void StopProjectile(CStateManager& mgr);
public:
CEnergyProjectile(bool active, const TToken<CWeaponDescription>& desc, EWeaponType type, const zeus::CTransform& xf,
EMaterialTypes excludeMat, const CDamageInfo& damage, TUniqueId uid, TAreaId aid, TUniqueId owner,
TUniqueId homingTarget, EProjectileAttrib attribs, bool underwater, const zeus::CVector3f& scale,
const std::optional<TLockedToken<CGenDescription>>& visorParticle, u16 visorSfx,
bool sendCollideMsg);
void SetCameraShake(const CCameraShakeData& data) {
x2fc_camShake = data;
x3d0_27_camShakeDirty = true;
}
void PlayImpactSound(const zeus::CVector3f& pos, EWeaponCollisionResponseTypes type);
void ChangeProjectileOwner(TUniqueId owner, CStateManager& mgr);
void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr);
void Accept(IVisitor& visitor);
void ResolveCollisionWithWorld(const CRayCastResult& res, CStateManager& mgr);
void ResolveCollisionWithActor(const CRayCastResult& res, CActor& act, CStateManager& mgr);
void Think(float dt, CStateManager& mgr);
void Render(CStateManager& mgr);
void AddToRenderer(const zeus::CFrustum& frustum, CStateManager& mgr);
void Touch(CActor& act, CStateManager& mgr);
virtual bool Explode(const zeus::CVector3f& pos, const zeus::CVector3f& normal, EWeaponCollisionResponseTypes type,
CStateManager& mgr, const CDamageVulnerability& dVuln, TUniqueId hitActor);
void Set3d0_26(bool v) { x3d0_26_ = v; }
};
} // namespace urde
<commit_msg>CEnergyProjectile: Mark functions as override<commit_after>#pragma once
#include "CGameProjectile.hpp"
#include "Camera/CCameraShakeData.hpp"
namespace urde {
class CEnergyProjectile : public CGameProjectile {
CSfxHandle x2e8_sfx;
zeus::CVector3f x2ec_dir;
float x2f8_mag;
CCameraShakeData x2fc_camShake;
bool x3d0_24_dead : 1;
bool x3d0_25_ : 1;
bool x3d0_26_ : 1;
bool x3d0_27_camShakeDirty : 1;
float x3d4_curTime = 0.f;
void StopProjectile(CStateManager& mgr);
public:
CEnergyProjectile(bool active, const TToken<CWeaponDescription>& desc, EWeaponType type, const zeus::CTransform& xf,
EMaterialTypes excludeMat, const CDamageInfo& damage, TUniqueId uid, TAreaId aid, TUniqueId owner,
TUniqueId homingTarget, EProjectileAttrib attribs, bool underwater, const zeus::CVector3f& scale,
const std::optional<TLockedToken<CGenDescription>>& visorParticle, u16 visorSfx,
bool sendCollideMsg);
void SetCameraShake(const CCameraShakeData& data) {
x2fc_camShake = data;
x3d0_27_camShakeDirty = true;
}
void PlayImpactSound(const zeus::CVector3f& pos, EWeaponCollisionResponseTypes type);
void ChangeProjectileOwner(TUniqueId owner, CStateManager& mgr);
void AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr) override;
void Accept(IVisitor& visitor) override;
void ResolveCollisionWithWorld(const CRayCastResult& res, CStateManager& mgr);
void ResolveCollisionWithActor(const CRayCastResult& res, CActor& act, CStateManager& mgr) override;
void Think(float dt, CStateManager& mgr) override;
void Render(CStateManager& mgr) override;
void AddToRenderer(const zeus::CFrustum& frustum, CStateManager& mgr) override;
void Touch(CActor& act, CStateManager& mgr) override;
virtual bool Explode(const zeus::CVector3f& pos, const zeus::CVector3f& normal, EWeaponCollisionResponseTypes type,
CStateManager& mgr, const CDamageVulnerability& dVuln, TUniqueId hitActor);
void Set3d0_26(bool v) { x3d0_26_ = v; }
};
} // namespace urde
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12. Mai 2009) $
Version: $Revision: 17179 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPlanarFigureWriter.h"
#include "mitkBasePropertySerializer.h"
#include <tinyxml.h>
mitk::PlanarFigureWriter::PlanarFigureWriter()
: m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Extension(".pf"),
m_MimeType("application/MITK.PlanarFigure"), m_Success(false)
{
this->SetNumberOfRequiredInputs( 1 );
this->SetNumberOfOutputs( 0 );
//this->SetNthOutput( 0, mitk::PlanarFigure::New().GetPointer() );
m_CanWriteToMemory = true;
}
mitk::PlanarFigureWriter::~PlanarFigureWriter()
{}
void mitk::PlanarFigureWriter::GenerateData()
{
m_Success = false;
if (!m_WriteToMemory && m_FileName.empty())
{
MITK_ERROR << "Could not write planar figures. File name is invalid";
throw std::invalid_argument("file name is empty");
}
TiXmlDocument document;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc....
document.LinkEndChild( decl );
TiXmlElement* version = new TiXmlElement("Version");
version->SetAttribute("Writer", __FILE__ );
version->SetAttribute("CVSRevision", "$Revision: 17055 $" );
version->SetAttribute("FileVersion", 1 );
document.LinkEndChild(version);
/* create xml element for each input */
for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i )
{
// Create root element for this PlanarFigure
InputType::Pointer pf = this->GetInput( i );
if (pf.IsNull())
continue;
TiXmlElement* pfElement = new TiXmlElement("PlanarFigure");
pfElement->SetAttribute("type", pf->GetNameOfClass());
document.LinkEndChild(pfElement);
PlanarFigure::VertexContainerType* vertices = pf->GetControlPoints();
if (vertices == NULL)
continue;
// Serialize property list of PlanarFigure
mitk::PropertyList::Pointer propertyList = pf->GetPropertyList();
mitk::PropertyList::PropertyMap::const_iterator it;
for ( it = propertyList->GetMap()->begin(); it != propertyList->GetMap()->end(); ++it )
{
// Create seralizer for this property
const mitk::BaseProperty* prop = it->second.first;
std::string serializerName = std::string( prop->GetNameOfClass() ) + "Serializer";
std::list< itk::LightObject::Pointer > allSerializers = itk::ObjectFactoryBase::CreateAllInstance(
serializerName.c_str() );
if ( allSerializers.size() != 1 )
{
// No or too many serializer(s) found, skip this property
continue;
}
mitk::BasePropertySerializer* serializer = dynamic_cast< mitk::BasePropertySerializer* >(
allSerializers.begin()->GetPointer() );
if ( serializer == NULL )
{
// Serializer not valid; skip this property
}
TiXmlElement* keyElement = new TiXmlElement( "property" );
keyElement->SetAttribute( "key", it->first );
keyElement->SetAttribute( "type", prop->GetNameOfClass() );
serializer->SetProperty( prop );
TiXmlElement* valueElement = NULL;
try
{
valueElement = serializer->Serialize();
}
catch (...)
{
}
if ( valueElement == NULL )
{
// Serialization failed; skip this property
continue;
}
// Add value to property element
keyElement->LinkEndChild( valueElement );
// Append serialized property to property list
pfElement->LinkEndChild( keyElement );
}
// Serialize control points of PlanarFigure
TiXmlElement* controlPointsElement = new TiXmlElement("ControlPoints");
pfElement->LinkEndChild(controlPointsElement);
for (unsigned int i = 0; i < pf->GetNumberOfControlPoints(); i++)
{
TiXmlElement* vElement = new TiXmlElement("Vertex");
vElement->SetAttribute("id", i);
vElement->SetDoubleAttribute("x", pf->GetControlPoint(i)[0]);
vElement->SetDoubleAttribute("y", pf->GetControlPoint(i)[1]);
controlPointsElement->LinkEndChild(vElement);
}
TiXmlElement* geoElement = new TiXmlElement("Geometry");
const PlaneGeometry* planeGeo = dynamic_cast<const PlaneGeometry*>(pf->GetGeometry2D());
if (planeGeo != NULL)
{
// Write parameters of IndexToWorldTransform of the PlaneGeometry
typedef mitk::AffineGeometryFrame3D::TransformType TransformType;
const TransformType* affineGeometry = planeGeo->GetIndexToWorldTransform();
const TransformType::ParametersType& parameters = affineGeometry->GetParameters();
TiXmlElement* vElement = new TiXmlElement( "transformParam" );
for ( unsigned int i = 0; i < affineGeometry->GetNumberOfParameters(); ++i )
{
std::stringstream paramName;
paramName << "param" << i;
vElement->SetDoubleAttribute( paramName.str().c_str(), parameters.GetElement( i ) );
}
geoElement->LinkEndChild( vElement );
// Write bounds of the PlaneGeometry
typedef mitk::Geometry3D::BoundsArrayType BoundsArrayType;
const BoundsArrayType& bounds = planeGeo->GetBounds();
vElement = new TiXmlElement( "boundsParam" );
for ( unsigned int i = 0; i < 6; ++i )
{
std::stringstream boundName;
boundName << "bound" << i;
vElement->SetDoubleAttribute( boundName.str().c_str(), bounds.GetElement( i ) );
}
geoElement->LinkEndChild( vElement );
// Write spacing and origin of the PlaneGeometry
Vector3D spacing = planeGeo->GetSpacing();
Point3D origin = planeGeo->GetOrigin();
geoElement->LinkEndChild(this->CreateXMLVectorElement("Spacing", spacing));
geoElement->LinkEndChild(this->CreateXMLVectorElement("Origin", origin));
pfElement->LinkEndChild(geoElement);
}
}
if(m_WriteToMemory)
{
// Declare a printer
TiXmlPrinter printer;
// attach it to the document you want to convert in to a std::string
document.Accept(&printer);
// Create memory buffer and print tinyxmldocument there...
m_MemoryBufferSize = printer.Size();
m_MemoryBuffer = new char[m_MemoryBufferSize];
memcpy(m_MemoryBuffer,printer.CStr(),m_MemoryBufferSize);
}
else
{
if (document.SaveFile( m_FileName) == false)
{
MITK_ERROR << "Could not write planar figures to " << m_FileName << "\nTinyXML reports '" << document.ErrorDesc() << "'";
throw std::ios_base::failure("Error during writing of planar figure xml file.");
}
}
m_Success = true;
}
void mitk::PlanarFigureWriter::ReleaseMemory()
{
if(m_MemoryBuffer != NULL)
{
delete [] m_MemoryBuffer;
}
}
TiXmlElement* mitk::PlanarFigureWriter::CreateXMLVectorElement(const char* name, itk::FixedArray<mitk::ScalarType, 3> v)
{
TiXmlElement* vElement = new TiXmlElement(name);
vElement->SetDoubleAttribute("x", v.GetElement(0));
vElement->SetDoubleAttribute("y", v.GetElement(1));
vElement->SetDoubleAttribute("z", v.GetElement(2));
return vElement;
}
void mitk::PlanarFigureWriter::ResizeInputs( const unsigned int& num )
{
//unsigned int prevNum = this->GetNumberOfInputs();
this->SetNumberOfInputs( num );
//for ( unsigned int i = prevNum; i < num; ++i )
//{
// this->SetNthInput( i, mitk::PlanarFigure::New().GetPointer() );
//}
}
void mitk::PlanarFigureWriter::SetInput( InputType* PlanarFigure )
{
this->ProcessObject::SetNthInput( 0, PlanarFigure );
}
void mitk::PlanarFigureWriter::SetInput( const unsigned int& id, InputType* PlanarFigure )
{
if ( id >= this->GetNumberOfInputs() )
this->ResizeInputs( id + 1 );
this->ProcessObject::SetNthInput( id, PlanarFigure );
}
mitk::PlanarFigure* mitk::PlanarFigureWriter::GetInput()
{
if ( this->GetNumberOfInputs() < 1 )
return NULL;
else
return dynamic_cast<InputType*> ( this->GetInput( 0 ) );
}
mitk::PlanarFigure* mitk::PlanarFigureWriter::GetInput( const unsigned int& num )
{
return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) );
}
bool mitk::PlanarFigureWriter::CanWriteDataType( DataNode* input )
{
if ( input == NULL )
return false;
mitk::BaseData* data = input->GetData();
if ( data == NULL)
return false;
mitk::PlanarFigure::Pointer PlanarFigure = dynamic_cast<mitk::PlanarFigure*>( data );
if( PlanarFigure.IsNull() )
return false;
// add code for special subclasses here
return true;
}
void mitk::PlanarFigureWriter::SetInput( DataNode* input )
{
if (this->CanWriteDataType(input))
this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::PlanarFigure*>( input->GetData() ) );
}
std::string mitk::PlanarFigureWriter::GetWritenMIMEType()
{
return m_MimeType;
}
std::vector<std::string> mitk::PlanarFigureWriter::GetPossibleFileExtensions()
{
std::vector<std::string> possibleFileExtensions;
possibleFileExtensions.push_back(m_Extension);
return possibleFileExtensions;
}
std::string mitk::PlanarFigureWriter::GetFileExtension()
{
return m_Extension;
}
<commit_msg>adapting PlanarFigureWriter to new point containers<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12. Mai 2009) $
Version: $Revision: 17179 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkPlanarFigureWriter.h"
#include "mitkBasePropertySerializer.h"
#include <tinyxml.h>
mitk::PlanarFigureWriter::PlanarFigureWriter()
: m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Extension(".pf"),
m_MimeType("application/MITK.PlanarFigure"), m_Success(false)
{
this->SetNumberOfRequiredInputs( 1 );
this->SetNumberOfOutputs( 0 );
//this->SetNthOutput( 0, mitk::PlanarFigure::New().GetPointer() );
m_CanWriteToMemory = true;
}
mitk::PlanarFigureWriter::~PlanarFigureWriter()
{}
void mitk::PlanarFigureWriter::GenerateData()
{
m_Success = false;
if (!m_WriteToMemory && m_FileName.empty())
{
MITK_ERROR << "Could not write planar figures. File name is invalid";
throw std::invalid_argument("file name is empty");
}
TiXmlDocument document;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc....
document.LinkEndChild( decl );
TiXmlElement* version = new TiXmlElement("Version");
version->SetAttribute("Writer", __FILE__ );
version->SetAttribute("CVSRevision", "$Revision: 17055 $" );
version->SetAttribute("FileVersion", 1 );
document.LinkEndChild(version);
/* create xml element for each input */
for ( unsigned int i = 0 ; i < this->GetNumberOfInputs(); ++i )
{
// Create root element for this PlanarFigure
InputType::Pointer pf = this->GetInput( i );
if (pf.IsNull())
continue;
TiXmlElement* pfElement = new TiXmlElement("PlanarFigure");
pfElement->SetAttribute("type", pf->GetNameOfClass());
document.LinkEndChild(pfElement);
if ( pf->GetNumberOfControlPoints() == 0 )
continue;
//PlanarFigure::VertexContainerType* vertices = pf->GetControlPoints();
//if (vertices == NULL)
// continue;
// Serialize property list of PlanarFigure
mitk::PropertyList::Pointer propertyList = pf->GetPropertyList();
mitk::PropertyList::PropertyMap::const_iterator it;
for ( it = propertyList->GetMap()->begin(); it != propertyList->GetMap()->end(); ++it )
{
// Create seralizer for this property
const mitk::BaseProperty* prop = it->second.first;
std::string serializerName = std::string( prop->GetNameOfClass() ) + "Serializer";
std::list< itk::LightObject::Pointer > allSerializers = itk::ObjectFactoryBase::CreateAllInstance(
serializerName.c_str() );
if ( allSerializers.size() != 1 )
{
// No or too many serializer(s) found, skip this property
continue;
}
mitk::BasePropertySerializer* serializer = dynamic_cast< mitk::BasePropertySerializer* >(
allSerializers.begin()->GetPointer() );
if ( serializer == NULL )
{
// Serializer not valid; skip this property
}
TiXmlElement* keyElement = new TiXmlElement( "property" );
keyElement->SetAttribute( "key", it->first );
keyElement->SetAttribute( "type", prop->GetNameOfClass() );
serializer->SetProperty( prop );
TiXmlElement* valueElement = NULL;
try
{
valueElement = serializer->Serialize();
}
catch (...)
{
}
if ( valueElement == NULL )
{
// Serialization failed; skip this property
continue;
}
// Add value to property element
keyElement->LinkEndChild( valueElement );
// Append serialized property to property list
pfElement->LinkEndChild( keyElement );
}
// Serialize control points of PlanarFigure
TiXmlElement* controlPointsElement = new TiXmlElement("ControlPoints");
pfElement->LinkEndChild(controlPointsElement);
for (unsigned int i = 0; i < pf->GetNumberOfControlPoints(); i++)
{
TiXmlElement* vElement = new TiXmlElement("Vertex");
vElement->SetAttribute("id", i);
vElement->SetDoubleAttribute("x", pf->GetControlPoint(i)[0]);
vElement->SetDoubleAttribute("y", pf->GetControlPoint(i)[1]);
controlPointsElement->LinkEndChild(vElement);
}
TiXmlElement* geoElement = new TiXmlElement("Geometry");
const PlaneGeometry* planeGeo = dynamic_cast<const PlaneGeometry*>(pf->GetGeometry2D());
if (planeGeo != NULL)
{
// Write parameters of IndexToWorldTransform of the PlaneGeometry
typedef mitk::AffineGeometryFrame3D::TransformType TransformType;
const TransformType* affineGeometry = planeGeo->GetIndexToWorldTransform();
const TransformType::ParametersType& parameters = affineGeometry->GetParameters();
TiXmlElement* vElement = new TiXmlElement( "transformParam" );
for ( unsigned int i = 0; i < affineGeometry->GetNumberOfParameters(); ++i )
{
std::stringstream paramName;
paramName << "param" << i;
vElement->SetDoubleAttribute( paramName.str().c_str(), parameters.GetElement( i ) );
}
geoElement->LinkEndChild( vElement );
// Write bounds of the PlaneGeometry
typedef mitk::Geometry3D::BoundsArrayType BoundsArrayType;
const BoundsArrayType& bounds = planeGeo->GetBounds();
vElement = new TiXmlElement( "boundsParam" );
for ( unsigned int i = 0; i < 6; ++i )
{
std::stringstream boundName;
boundName << "bound" << i;
vElement->SetDoubleAttribute( boundName.str().c_str(), bounds.GetElement( i ) );
}
geoElement->LinkEndChild( vElement );
// Write spacing and origin of the PlaneGeometry
Vector3D spacing = planeGeo->GetSpacing();
Point3D origin = planeGeo->GetOrigin();
geoElement->LinkEndChild(this->CreateXMLVectorElement("Spacing", spacing));
geoElement->LinkEndChild(this->CreateXMLVectorElement("Origin", origin));
pfElement->LinkEndChild(geoElement);
}
}
if(m_WriteToMemory)
{
// Declare a printer
TiXmlPrinter printer;
// attach it to the document you want to convert in to a std::string
document.Accept(&printer);
// Create memory buffer and print tinyxmldocument there...
m_MemoryBufferSize = printer.Size();
m_MemoryBuffer = new char[m_MemoryBufferSize];
memcpy(m_MemoryBuffer,printer.CStr(),m_MemoryBufferSize);
}
else
{
if (document.SaveFile( m_FileName) == false)
{
MITK_ERROR << "Could not write planar figures to " << m_FileName << "\nTinyXML reports '" << document.ErrorDesc() << "'";
throw std::ios_base::failure("Error during writing of planar figure xml file.");
}
}
m_Success = true;
}
void mitk::PlanarFigureWriter::ReleaseMemory()
{
if(m_MemoryBuffer != NULL)
{
delete [] m_MemoryBuffer;
}
}
TiXmlElement* mitk::PlanarFigureWriter::CreateXMLVectorElement(const char* name, itk::FixedArray<mitk::ScalarType, 3> v)
{
TiXmlElement* vElement = new TiXmlElement(name);
vElement->SetDoubleAttribute("x", v.GetElement(0));
vElement->SetDoubleAttribute("y", v.GetElement(1));
vElement->SetDoubleAttribute("z", v.GetElement(2));
return vElement;
}
void mitk::PlanarFigureWriter::ResizeInputs( const unsigned int& num )
{
//unsigned int prevNum = this->GetNumberOfInputs();
this->SetNumberOfInputs( num );
//for ( unsigned int i = prevNum; i < num; ++i )
//{
// this->SetNthInput( i, mitk::PlanarFigure::New().GetPointer() );
//}
}
void mitk::PlanarFigureWriter::SetInput( InputType* PlanarFigure )
{
this->ProcessObject::SetNthInput( 0, PlanarFigure );
}
void mitk::PlanarFigureWriter::SetInput( const unsigned int& id, InputType* PlanarFigure )
{
if ( id >= this->GetNumberOfInputs() )
this->ResizeInputs( id + 1 );
this->ProcessObject::SetNthInput( id, PlanarFigure );
}
mitk::PlanarFigure* mitk::PlanarFigureWriter::GetInput()
{
if ( this->GetNumberOfInputs() < 1 )
return NULL;
else
return dynamic_cast<InputType*> ( this->GetInput( 0 ) );
}
mitk::PlanarFigure* mitk::PlanarFigureWriter::GetInput( const unsigned int& num )
{
return dynamic_cast<InputType*> ( this->ProcessObject::GetInput( num ) );
}
bool mitk::PlanarFigureWriter::CanWriteDataType( DataNode* input )
{
if ( input == NULL )
return false;
mitk::BaseData* data = input->GetData();
if ( data == NULL)
return false;
mitk::PlanarFigure::Pointer PlanarFigure = dynamic_cast<mitk::PlanarFigure*>( data );
if( PlanarFigure.IsNull() )
return false;
// add code for special subclasses here
return true;
}
void mitk::PlanarFigureWriter::SetInput( DataNode* input )
{
if (this->CanWriteDataType(input))
this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::PlanarFigure*>( input->GetData() ) );
}
std::string mitk::PlanarFigureWriter::GetWritenMIMEType()
{
return m_MimeType;
}
std::vector<std::string> mitk::PlanarFigureWriter::GetPossibleFileExtensions()
{
std::vector<std::string> possibleFileExtensions;
possibleFileExtensions.push_back(m_Extension);
return possibleFileExtensions;
}
std::string mitk::PlanarFigureWriter::GetFileExtension()
{
return m_Extension;
}
<|endoftext|>
|
<commit_before>//
// AppleGCR.cpp
// Clock Signal
//
// Created by Thomas Harte on 21/04/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "AppleGCR.hpp"
namespace {
const unsigned int five_and_three_mapping[] = {
0xab, 0xad, 0xae, 0xaf, 0xb5, 0xb6, 0xb7, 0xba,
0xbb, 0xbd, 0xbe, 0xbf, 0xd6, 0xd7, 0xda, 0xdb,
0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xed, 0xee, 0xef,
0xf5, 0xf6, 0xf7, 0xfa, 0xfb, 0xfd, 0xfe, 0xff
};
const uint8_t six_and_two_mapping[] = {
0x96, 0x97, 0x9a, 0x9b, 0x9d, 0x9e, 0x9f, 0xa6,
0xa7, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb9, 0xba, 0xbb, 0xbc,
0xbd, 0xbe, 0xbf, 0xcb, 0xcd, 0xce, 0xcf, 0xd3,
0xd6, 0xd7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde,
0xdf, 0xe5, 0xe6, 0xe7, 0xe9, 0xea, 0xeb, 0xec,
0xed, 0xee, 0xef, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6,
0xf7, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
/*!
Produces a PCM segment containing @c length sync bytes, each aligned to the beginning of
a @c bit_size -sized window.
*/
Storage::Disk::PCMSegment sync(int length, int bit_size) {
Storage::Disk::PCMSegment segment;
// Allocate sufficient storage.
segment.data.resize(static_cast<size_t>(((length * bit_size) + 7) >> 3), 0);
while(length--) {
segment.data[segment.number_of_bits >> 3] |= 0xff >> (segment.number_of_bits & 7);
if(segment.number_of_bits & 7) {
segment.data[1 + (segment.number_of_bits >> 3)] |= 0xff << (8 - (segment.number_of_bits & 7));
}
segment.number_of_bits += static_cast<unsigned int>(bit_size);
}
return segment;
}
}
using namespace Storage::Encodings;
/*void AppleGCR::encode_five_and_three_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[0] >> 3 ));
destination[1] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[0] << 2) | (source[1] >> 6) ));
destination[2] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[1] >> 1 ));
destination[3] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[1] << 4) | (source[2] >> 4) ));
destination[4] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[2] << 1) | (source[3] >> 7) ));
destination[5] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[3] >> 2 ));
destination[6] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[3] << 3) | (source[4] >> 5) ));
destination[7] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[4] ));
}*/
/*void AppleGCR::encode_six_and_two_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[0] >> 2 ));
destination[1] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[0] << 4) | (source[1] >> 4) ));
destination[2] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[1] << 2) | (source[2] >> 6) ));
destination[3] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[2] ));
}*/
Storage::Disk::PCMSegment AppleGCR::six_and_two_sync(int length) {
return sync(length, 10);
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_sync(int length) {
return sync(length, 9);
}
Storage::Disk::PCMSegment AppleGCR::header(uint8_t volume, uint8_t track, uint8_t sector) {
const uint8_t checksum = volume ^ track ^ sector;
// Apple headers are encoded using an FM-esque scheme rather than 6 and 2, or 5 and 3.
Storage::Disk::PCMSegment segment;
segment.data.resize(14);
segment.number_of_bits = 14*8;
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
#define WriteFM(index, value) \
segment.data[index+0] = static_cast<uint8_t>(((value) >> 1) | 0xaa); \
segment.data[index+1] = static_cast<uint8_t>((value) | 0xaa); \
WriteFM(3, volume);
WriteFM(5, track);
WriteFM(7, sector);
WriteFM(9, checksum);
#undef WriteFM
segment.data[11] = epilogue[0];
segment.data[12] = epilogue[1];
segment.data[13] = epilogue[2];
return segment;
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(410 + 7);
segment.data[0] = data_prologue[0];
segment.data[1] = data_prologue[1];
segment.data[2] = data_prologue[2];
segment.data[414] = epilogue[0];
segment.data[411] = epilogue[1];
segment.data[416] = epilogue[2];
// std::size_t source_pointer = 0;
// std::size_t destination_pointer = 3;
// while(source_pointer < 255) {
// encode_five_and_three_block(&segment.data[destination_pointer], &source[source_pointer]);
//
// source_pointer += 5;
// destination_pointer += 8;
// }
return segment;
}
Storage::Disk::PCMSegment AppleGCR::six_and_two_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(349);
segment.number_of_bits = static_cast<unsigned int>(segment.data.size() * 8);
// Add the prologue and epilogue.
segment.data[0] = data_prologue[0];
segment.data[1] = data_prologue[1];
segment.data[2] = data_prologue[2];
segment.data[346] = epilogue[0];
segment.data[347] = epilogue[1];
segment.data[348] = epilogue[2];
// Fill in byte values: the first 86 bytes contain shuffled
// and combined copies of the bottom two bits of the sector
// contents; the 256 bytes afterwards are the remaining
// six bits.
const uint8_t bit_shuffle[] = {0, 2, 1, 3};
for(std::size_t c = 0; c < 84; ++c) {
segment.data[3 + c] = bit_shuffle[source[c]&3];
if(c + 86 < 256) segment.data[3 + c] |= bit_shuffle[source[c + 86]&3] << 2;
if(c + 172 < 256) segment.data[3 + c] |= bit_shuffle[source[c + 172]&3] << 4;
}
for(std::size_t c = 0; c < 256; ++c) {
segment.data[3 + 85 + 1 + c] = source[c] >> 2;
}
// Exclusive OR each byte with the one before it.
segment.data[345] = segment.data[344];
std::size_t location = 344;
while(location > 3) {
segment.data[location] ^= segment.data[location-1];
--location;
}
// Map six-bit values up to full bytes.
for(std::size_t c = 0; c < 343; ++c) {
segment.data[3 + c] = six_and_two_mapping[segment.data[3 + c]];
}
return segment;
}
<commit_msg>Corrects final two bytes of Apple GCR low nibble encoding.<commit_after>//
// AppleGCR.cpp
// Clock Signal
//
// Created by Thomas Harte on 21/04/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "AppleGCR.hpp"
namespace {
const unsigned int five_and_three_mapping[] = {
0xab, 0xad, 0xae, 0xaf, 0xb5, 0xb6, 0xb7, 0xba,
0xbb, 0xbd, 0xbe, 0xbf, 0xd6, 0xd7, 0xda, 0xdb,
0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xed, 0xee, 0xef,
0xf5, 0xf6, 0xf7, 0xfa, 0xfb, 0xfd, 0xfe, 0xff
};
const uint8_t six_and_two_mapping[] = {
0x96, 0x97, 0x9a, 0x9b, 0x9d, 0x9e, 0x9f, 0xa6,
0xa7, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb9, 0xba, 0xbb, 0xbc,
0xbd, 0xbe, 0xbf, 0xcb, 0xcd, 0xce, 0xcf, 0xd3,
0xd6, 0xd7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde,
0xdf, 0xe5, 0xe6, 0xe7, 0xe9, 0xea, 0xeb, 0xec,
0xed, 0xee, 0xef, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6,
0xf7, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
/*!
Produces a PCM segment containing @c length sync bytes, each aligned to the beginning of
a @c bit_size -sized window.
*/
Storage::Disk::PCMSegment sync(int length, int bit_size) {
Storage::Disk::PCMSegment segment;
// Allocate sufficient storage.
segment.data.resize(static_cast<size_t>(((length * bit_size) + 7) >> 3), 0);
while(length--) {
segment.data[segment.number_of_bits >> 3] |= 0xff >> (segment.number_of_bits & 7);
if(segment.number_of_bits & 7) {
segment.data[1 + (segment.number_of_bits >> 3)] |= 0xff << (8 - (segment.number_of_bits & 7));
}
segment.number_of_bits += static_cast<unsigned int>(bit_size);
}
return segment;
}
}
using namespace Storage::Encodings;
/*void AppleGCR::encode_five_and_three_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[0] >> 3 ));
destination[1] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[0] << 2) | (source[1] >> 6) ));
destination[2] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[1] >> 1 ));
destination[3] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[1] << 4) | (source[2] >> 4) ));
destination[4] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[2] << 1) | (source[3] >> 7) ));
destination[5] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[3] >> 2 ));
destination[6] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[3] << 3) | (source[4] >> 5) ));
destination[7] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[4] ));
}*/
/*void AppleGCR::encode_six_and_two_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[0] >> 2 ));
destination[1] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[0] << 4) | (source[1] >> 4) ));
destination[2] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[1] << 2) | (source[2] >> 6) ));
destination[3] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[2] ));
}*/
Storage::Disk::PCMSegment AppleGCR::six_and_two_sync(int length) {
return sync(length, 10);
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_sync(int length) {
return sync(length, 9);
}
Storage::Disk::PCMSegment AppleGCR::header(uint8_t volume, uint8_t track, uint8_t sector) {
const uint8_t checksum = volume ^ track ^ sector;
// Apple headers are encoded using an FM-esque scheme rather than 6 and 2, or 5 and 3.
Storage::Disk::PCMSegment segment;
segment.data.resize(14);
segment.number_of_bits = 14*8;
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
#define WriteFM(index, value) \
segment.data[index+0] = static_cast<uint8_t>(((value) >> 1) | 0xaa); \
segment.data[index+1] = static_cast<uint8_t>((value) | 0xaa); \
WriteFM(3, volume);
WriteFM(5, track);
WriteFM(7, sector);
WriteFM(9, checksum);
#undef WriteFM
segment.data[11] = epilogue[0];
segment.data[12] = epilogue[1];
segment.data[13] = epilogue[2];
return segment;
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(410 + 7);
segment.data[0] = data_prologue[0];
segment.data[1] = data_prologue[1];
segment.data[2] = data_prologue[2];
segment.data[414] = epilogue[0];
segment.data[411] = epilogue[1];
segment.data[416] = epilogue[2];
// std::size_t source_pointer = 0;
// std::size_t destination_pointer = 3;
// while(source_pointer < 255) {
// encode_five_and_three_block(&segment.data[destination_pointer], &source[source_pointer]);
//
// source_pointer += 5;
// destination_pointer += 8;
// }
return segment;
}
Storage::Disk::PCMSegment AppleGCR::six_and_two_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(349);
segment.number_of_bits = static_cast<unsigned int>(segment.data.size() * 8);
// Add the prologue and epilogue.
segment.data[0] = data_prologue[0];
segment.data[1] = data_prologue[1];
segment.data[2] = data_prologue[2];
segment.data[346] = epilogue[0];
segment.data[347] = epilogue[1];
segment.data[348] = epilogue[2];
// Fill in byte values: the first 86 bytes contain shuffled
// and combined copies of the bottom two bits of the sector
// contents; the 256 bytes afterwards are the remaining
// six bits.
const uint8_t bit_shuffle[] = {0, 2, 1, 3};
for(std::size_t c = 0; c < 84; ++c) {
segment.data[3 + c] =
static_cast<uint8_t>(
bit_shuffle[source[c]&3] |
(bit_shuffle[source[c + 86]&3] << 2) |
(bit_shuffle[source[c + 172]&3] << 4)
);
}
segment.data[87] =
static_cast<uint8_t>(
(bit_shuffle[source[84]&3] << 0) |
(bit_shuffle[source[170]&3] << 2)
);
segment.data[88] =
static_cast<uint8_t>(
(bit_shuffle[source[85]&3] << 0) |
(bit_shuffle[source[171]&3] << 2)
);
for(std::size_t c = 0; c < 256; ++c) {
segment.data[3 + 86 + c] = source[c] >> 2;
}
// Exclusive OR each byte with the one before it.
segment.data[345] = segment.data[344];
std::size_t location = 344;
while(location > 3) {
segment.data[location] ^= segment.data[location-1];
--location;
}
// Map six-bit values up to full bytes.
for(std::size_t c = 0; c < 343; ++c) {
segment.data[3 + c] = six_and_two_mapping[segment.data[3 + c]];
}
return segment;
}
<|endoftext|>
|
<commit_before>#include "common/WindowDescriptors.hpp"
#include "widgets/Window.hpp"
namespace chatterino {
namespace {
QJsonArray loadWindowArray(const QString &settingsPath)
{
QFile file(settingsPath);
file.open(QIODevice::ReadOnly);
QByteArray data = file.readAll();
QJsonDocument document = QJsonDocument::fromJson(data);
QJsonArray windows_arr = document.object().value("windows").toArray();
return windows_arr;
}
template <typename T>
T loadNodes(const QJsonObject &obj)
{
static_assert("loadNodes must be called with the SplitNodeDescriptor "
"or ContainerNodeDescriptor type");
}
template <>
SplitNodeDescriptor loadNodes(const QJsonObject &root)
{
SplitNodeDescriptor descriptor;
descriptor.flexH_ = root.value("flexh").toDouble(1.0);
descriptor.flexV_ = root.value("flexv").toDouble(1.0);
auto data = root.value("data").toObject();
SplitDescriptor::loadFromJSON(descriptor, root, data);
return descriptor;
}
template <>
ContainerNodeDescriptor loadNodes(const QJsonObject &root)
{
ContainerNodeDescriptor descriptor;
descriptor.flexH_ = root.value("flexh").toDouble(1.0);
descriptor.flexV_ = root.value("flexv").toDouble(1.0);
descriptor.vertical_ = root.value("type").toString() == "vertical";
for (QJsonValue _val : root.value("items").toArray())
{
auto _obj = _val.toObject();
auto _type = _obj.value("type");
if (_type == "split")
{
descriptor.items_.emplace_back(
loadNodes<SplitNodeDescriptor>(_obj));
}
else
{
descriptor.items_.emplace_back(
loadNodes<ContainerNodeDescriptor>(_obj));
}
}
return descriptor;
}
} // namespace
void SplitDescriptor::loadFromJSON(SplitDescriptor &descriptor,
const QJsonObject &root,
const QJsonObject &data)
{
descriptor.type_ = data.value("type").toString();
descriptor.server_ = data.value("server").toInt(-1);
if (data.contains("channel"))
{
descriptor.channelName_ = data.value("channel").toString();
}
else
{
descriptor.channelName_ = data.value("name").toString();
}
}
WindowLayout WindowLayout::loadFromFile(const QString &path)
{
WindowLayout layout;
bool hasSetAMainWindow = false;
// "deserialize"
for (const QJsonValue &window_val : loadWindowArray(path))
{
QJsonObject window_obj = window_val.toObject();
WindowDescriptor window;
// Load window type
QString type_val = window_obj.value("type").toString();
auto type = type_val == "main" ? WindowType::Main : WindowType::Popup;
if (type == WindowType::Main)
{
if (hasSetAMainWindow)
{
qDebug()
<< "Window Layout file contains more than one Main window "
"- demoting to Popup type";
type = WindowType::Popup;
}
hasSetAMainWindow = true;
}
window.type_ = type;
// Load window state
if (window_obj.value("state") == "minimized")
{
window.state_ = WindowDescriptor::State::Minimized;
}
else if (window_obj.value("state") == "maximized")
{
window.state_ = WindowDescriptor::State::Maximized;
}
// Load window geometry
{
int x = window_obj.value("x").toInt(-1);
int y = window_obj.value("y").toInt(-1);
int width = window_obj.value("width").toInt(-1);
int height = window_obj.value("height").toInt(-1);
window.geometry_ = QRect(x, y, width, height);
}
bool hasSetASelectedTab = false;
// Load window tabs
QJsonArray tabs = window_obj.value("tabs").toArray();
for (QJsonValue tab_val : tabs)
{
TabDescriptor tab;
QJsonObject tab_obj = tab_val.toObject();
// Load tab custom title
QJsonValue title_val = tab_obj.value("title");
if (title_val.isString())
{
tab.customTitle_ = title_val.toString();
}
// Load tab selected state
tab.selected_ = tab_obj.value("selected").toBool(false);
if (tab.selected_)
{
if (hasSetASelectedTab)
{
qDebug() << "Window contains more than one selected tab - "
"demoting to unselected";
tab.selected_ = false;
}
hasSetASelectedTab = true;
}
// Load tab "highlightsEnabled" state
tab.highlightsEnabled_ =
tab_obj.value("highlightsEnabled").toBool(true);
QJsonObject splitRoot = tab_obj.value("splits2").toObject();
// Load tab splits
if (!splitRoot.isEmpty())
{
// root type
auto nodeType = splitRoot.value("type").toString();
if (nodeType == "split")
{
tab.rootNode_ = loadNodes<SplitNodeDescriptor>(splitRoot);
}
else if (nodeType == "horizontal" || nodeType == "vertical")
{
tab.rootNode_ =
loadNodes<ContainerNodeDescriptor>(splitRoot);
}
}
window.tabs_.emplace_back(std::move(tab));
}
// Load emote popup position
QJsonObject emote_popup_obj = window_obj.value("emotePopup").toObject();
layout.emotePopupPos_ = QPoint(emote_popup_obj.value("x").toInt(),
emote_popup_obj.value("y").toInt());
layout.windows_.emplace_back(std::move(window));
}
return layout;
}
} // namespace chatterino
<commit_msg>Make moderation mode persist (#2035)<commit_after>#include "common/WindowDescriptors.hpp"
#include "widgets/Window.hpp"
namespace chatterino {
namespace {
QJsonArray loadWindowArray(const QString &settingsPath)
{
QFile file(settingsPath);
file.open(QIODevice::ReadOnly);
QByteArray data = file.readAll();
QJsonDocument document = QJsonDocument::fromJson(data);
QJsonArray windows_arr = document.object().value("windows").toArray();
return windows_arr;
}
template <typename T>
T loadNodes(const QJsonObject &obj)
{
static_assert("loadNodes must be called with the SplitNodeDescriptor "
"or ContainerNodeDescriptor type");
}
template <>
SplitNodeDescriptor loadNodes(const QJsonObject &root)
{
SplitNodeDescriptor descriptor;
descriptor.flexH_ = root.value("flexh").toDouble(1.0);
descriptor.flexV_ = root.value("flexv").toDouble(1.0);
auto data = root.value("data").toObject();
SplitDescriptor::loadFromJSON(descriptor, root, data);
return descriptor;
}
template <>
ContainerNodeDescriptor loadNodes(const QJsonObject &root)
{
ContainerNodeDescriptor descriptor;
descriptor.flexH_ = root.value("flexh").toDouble(1.0);
descriptor.flexV_ = root.value("flexv").toDouble(1.0);
descriptor.vertical_ = root.value("type").toString() == "vertical";
for (QJsonValue _val : root.value("items").toArray())
{
auto _obj = _val.toObject();
auto _type = _obj.value("type");
if (_type == "split")
{
descriptor.items_.emplace_back(
loadNodes<SplitNodeDescriptor>(_obj));
}
else
{
descriptor.items_.emplace_back(
loadNodes<ContainerNodeDescriptor>(_obj));
}
}
return descriptor;
}
} // namespace
void SplitDescriptor::loadFromJSON(SplitDescriptor &descriptor,
const QJsonObject &root,
const QJsonObject &data)
{
descriptor.type_ = data.value("type").toString();
descriptor.server_ = data.value("server").toInt(-1);
descriptor.moderationMode_ = root.value("moderationMode").toBool();
if (data.contains("channel"))
{
descriptor.channelName_ = data.value("channel").toString();
}
else
{
descriptor.channelName_ = data.value("name").toString();
}
}
WindowLayout WindowLayout::loadFromFile(const QString &path)
{
WindowLayout layout;
bool hasSetAMainWindow = false;
// "deserialize"
for (const QJsonValue &window_val : loadWindowArray(path))
{
QJsonObject window_obj = window_val.toObject();
WindowDescriptor window;
// Load window type
QString type_val = window_obj.value("type").toString();
auto type = type_val == "main" ? WindowType::Main : WindowType::Popup;
if (type == WindowType::Main)
{
if (hasSetAMainWindow)
{
qDebug()
<< "Window Layout file contains more than one Main window "
"- demoting to Popup type";
type = WindowType::Popup;
}
hasSetAMainWindow = true;
}
window.type_ = type;
// Load window state
if (window_obj.value("state") == "minimized")
{
window.state_ = WindowDescriptor::State::Minimized;
}
else if (window_obj.value("state") == "maximized")
{
window.state_ = WindowDescriptor::State::Maximized;
}
// Load window geometry
{
int x = window_obj.value("x").toInt(-1);
int y = window_obj.value("y").toInt(-1);
int width = window_obj.value("width").toInt(-1);
int height = window_obj.value("height").toInt(-1);
window.geometry_ = QRect(x, y, width, height);
}
bool hasSetASelectedTab = false;
// Load window tabs
QJsonArray tabs = window_obj.value("tabs").toArray();
for (QJsonValue tab_val : tabs)
{
TabDescriptor tab;
QJsonObject tab_obj = tab_val.toObject();
// Load tab custom title
QJsonValue title_val = tab_obj.value("title");
if (title_val.isString())
{
tab.customTitle_ = title_val.toString();
}
// Load tab selected state
tab.selected_ = tab_obj.value("selected").toBool(false);
if (tab.selected_)
{
if (hasSetASelectedTab)
{
qDebug() << "Window contains more than one selected tab - "
"demoting to unselected";
tab.selected_ = false;
}
hasSetASelectedTab = true;
}
// Load tab "highlightsEnabled" state
tab.highlightsEnabled_ =
tab_obj.value("highlightsEnabled").toBool(true);
QJsonObject splitRoot = tab_obj.value("splits2").toObject();
// Load tab splits
if (!splitRoot.isEmpty())
{
// root type
auto nodeType = splitRoot.value("type").toString();
if (nodeType == "split")
{
tab.rootNode_ = loadNodes<SplitNodeDescriptor>(splitRoot);
}
else if (nodeType == "horizontal" || nodeType == "vertical")
{
tab.rootNode_ =
loadNodes<ContainerNodeDescriptor>(splitRoot);
}
}
window.tabs_.emplace_back(std::move(tab));
}
// Load emote popup position
QJsonObject emote_popup_obj = window_obj.value("emotePopup").toObject();
layout.emotePopupPos_ = QPoint(emote_popup_obj.value("x").toInt(),
emote_popup_obj.value("y").toInt());
layout.windows_.emplace_back(std::move(window));
}
return layout;
}
} // namespace chatterino
<|endoftext|>
|
<commit_before>#include "SINSymbolTable.h"
#include "SINAssert.h"
#define ASSERT_CURRENT_SCOPE() SINASSERT(currScope < table.size())
#define ASSERT_GIVEN_SCOPE() SINASSERT(scope < table.size())
#define ASSERT_SCOPE(SCOPE) SINASSERT(SCOPE < table.size())
#define RETURN_VALUE(SCOPE, FUNCTION_NAME, ARGUMENT) ASSERT_SCOPE(SCOPE); \
return table[SCOPE].FUNCTION_NAME(ARGUMENT)
namespace SIN {
//-----------------------------------------------------------------
SymbolTable::SymbolTable(void) {
table.reserve(20);
table.push_back(VariableHolder());
currScope = 0;
}
SymbolTable::~SymbolTable() {}
//-----------------------------------------------------------------
// in current and smaller scopes
SymbolTable::elem_t& SymbolTable::Lookup(const name_t& name) {
SINASSERT(!"not implemented");
RETURN_VALUE(currScope, LookupArgument, name);
}
//-----------------------------------------------------------------
// in given scope
SymbolTable::elem_t& SymbolTable::Lookup(const scope_id& scope, const name_t& name)
{ RETURN_VALUE(scope, LookupArgument, name); }
//-----------------------------------------------------------------
// in current scope
SymbolTable::elem_t& SymbolTable::LookupOnlyInCurrentScope(const name_t& name)
{ RETURN_VALUE(currScope, LookupArgument, name); }
//-----------------------------------------------------------------
// in current scope
SymbolTable::elem_t& SymbolTable::LookupByIndex(const unsigned int index)
{ RETURN_VALUE(currScope, Argument, index); }
//-----------------------------------------------------------------
// in given scope
SymbolTable::elem_t& SymbolTable::LookupByIndex(const scope_id& scope, const unsigned int index)
{ RETURN_VALUE(scope, Argument, index); }
//-----------------------------------------------------------------
// only in current scope
void SymbolTable::Insert(const name_t& name, const SymbolTable::elem_t& element) {
ASSERT_CURRENT_SCOPE();
table[currScope].AppendArgument(name, element);
}
//-----------------------------------------------------------------
void SymbolTable::IncreaseScope(void) {
table.push_back(VariableHolder());
++currScope;
}
//-----------------------------------------------------------------
void SymbolTable::DecreaseScope(void) {
SINASSERT(!"not implemented");
}
//-----------------------------------------------------------------
const SymbolTable::scope_id SymbolTable::CurrentScope(void) const
{ return currScope; }
//-----------------------------------------------------------------
// current scope
unsigned int SymbolTable::NumberOfSymbols(void) const {
ASSERT_CURRENT_SCOPE();
return table[currScope].NumberOfArguments();
}
//-----------------------------------------------------------------
// in given scope
unsigned int SymbolTable::NumberOfSymbols(const scope_id& scope) const {
ASSERT_GIVEN_SCOPE();
return table[scope].NumberOfArguments();
}
#define FOR_EACH_SYMBOL() return EntryHandler()
/*ASSERT_CURRENT_SCOPE(); \
return table[currScope].for_each_argument(eh)*/
//-----------------------------------------------------------------
// in current scope
SymbolTable::EntryHandler& SymbolTable::for_each_symbol(SymbolTable::EntryHandler& eh) const
{ FOR_EACH_SYMBOL(); }
//-----------------------------------------------------------------
// in current scope
const SymbolTable::EntryHandler& SymbolTable::for_each_symbol(const SymbolTable::EntryHandler& eh) const
{ FOR_EACH_SYMBOL(); }
}<commit_msg>* Implemented SymbolTable::for_each_symbol<commit_after>#include "SINSymbolTable.h"
#include "SINAssert.h"
#define ASSERT_CURRENT_SCOPE() SINASSERT(currScope < table.size())
#define ASSERT_GIVEN_SCOPE() SINASSERT(scope < table.size())
#define ASSERT_SCOPE(SCOPE) SINASSERT(SCOPE < table.size())
#define RETURN_VALUE(SCOPE, FUNCTION_NAME, ARGUMENT) ASSERT_SCOPE(SCOPE); \
return table[SCOPE].FUNCTION_NAME(ARGUMENT)
namespace SIN {
//-----------------------------------------------------------------
SymbolTable::SymbolTable(void) {
table.reserve(20);
table.push_back(VariableHolder());
currScope = 0;
}
SymbolTable::~SymbolTable() {}
//-----------------------------------------------------------------
// in current and smaller scopes
SymbolTable::elem_t& SymbolTable::Lookup(const name_t& name) {
SINASSERT(!"not implemented");
RETURN_VALUE(currScope, LookupArgument, name);
}
//-----------------------------------------------------------------
// in given scope
SymbolTable::elem_t& SymbolTable::Lookup(const scope_id& scope, const name_t& name)
{ RETURN_VALUE(scope, LookupArgument, name); }
//-----------------------------------------------------------------
// in current scope
SymbolTable::elem_t& SymbolTable::LookupOnlyInCurrentScope(const name_t& name)
{ RETURN_VALUE(currScope, LookupArgument, name); }
//-----------------------------------------------------------------
// in current scope
SymbolTable::elem_t& SymbolTable::LookupByIndex(const unsigned int index)
{ RETURN_VALUE(currScope, Argument, index); }
//-----------------------------------------------------------------
// in given scope
SymbolTable::elem_t& SymbolTable::LookupByIndex(const scope_id& scope, const unsigned int index)
{ RETURN_VALUE(scope, Argument, index); }
//-----------------------------------------------------------------
// only in current scope
void SymbolTable::Insert(const name_t& name, const SymbolTable::elem_t& element) {
ASSERT_CURRENT_SCOPE();
table[currScope].AppendArgument(name, element);
}
//-----------------------------------------------------------------
void SymbolTable::IncreaseScope(void) {
table.push_back(VariableHolder());
++currScope;
}
//-----------------------------------------------------------------
void SymbolTable::DecreaseScope(void) {
SINASSERT(!"not implemented");
}
//-----------------------------------------------------------------
const SymbolTable::scope_id SymbolTable::CurrentScope(void) const
{ return currScope; }
//-----------------------------------------------------------------
// current scope
unsigned int SymbolTable::NumberOfSymbols(void) const {
ASSERT_CURRENT_SCOPE();
return table[currScope].NumberOfArguments();
}
//-----------------------------------------------------------------
// in given scope
unsigned int SymbolTable::NumberOfSymbols(const scope_id& scope) const {
ASSERT_GIVEN_SCOPE();
return table[scope].NumberOfArguments();
}
struct CallableToEntryHolderAdaptor: public VariableHolder::Callable {
typedef VariableHolder::Entry entry_t;
typedef SymbolTable::EntryHandler handler_t;
handler_t& entry_handler;
handler_t const& const_entry_handler;
CallableToEntryHolderAdaptor(handler_t& eh): entry_handler(eh), const_entry_handler(eh) { }
CallableToEntryHolderAdaptor(handler_t const& eh): entry_handler(*static_cast<handler_t*>(0x00)), const_entry_handler(eh) { }
virtual ~CallableToEntryHolderAdaptor(void) { }
virtual bool operator ()(entry_t const& _entry)
{ return entry_handler(_entry.name, _entry.value); }
virtual bool operator ()(entry_t const& _entry) const
{ return const_entry_handler(_entry.name, _entry.value); }
}; // struct CallableToEntryHolderAdaptor
//-----------------------------------------------------------------
// in current scope
SymbolTable::EntryHandler& SymbolTable::for_each_symbol(SymbolTable::EntryHandler& eh) const {
// TODO koutsop tidy up -- add your asserts and stuff
CallableToEntryHolderAdaptor ceac(eh);
table[CurrentScope()].for_each_argument(ceac);
return eh;
}
//-----------------------------------------------------------------
// in current scope
const SymbolTable::EntryHandler& SymbolTable::for_each_symbol(const SymbolTable::EntryHandler& eh) const {
// TODO koutsop tidy up -- add your asserts and stuff
table[CurrentScope()].for_each_argument(CallableToEntryHolderAdaptor(eh));
return eh;
}
}<|endoftext|>
|
<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>
#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
//#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"
#include <vector>
#include <iostream>
#include <wiringPi.h> //compile with -lwiringPi
using namespace std;
vector<Sensor*> motionSensors; //Vector of the sensors
vector<Light*> lights; //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam; //Pointer to the camera
Log* log;
int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();
int main() {
init();
while(1) {
updateSensors();
checkAnomaly();
checkCam();
}
}
/*Init for the main*/
void init() {
wiringPiSetupGpio();
I2CCom i2c(I2CLOC); //the i2c to communicate with sensor
Light x(22);
MotionSensor s1(0xFC,i2c);
MotionSensor s2(0xBC,i2c);
MotionSensor s3(0xEC,i2c);
PressureSensor s4(0x06, i2c);
Log l1(LOG);
Camera c1;
cam = &c1;
log = &l1;
pressureSensor = &s4;
motionSensors.push_back(&s1);
motionSensors.push_back(&s2);
motionSensors.push_back(&s3);
lights.push_back(&x);
active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
//update van elke sensor de value en de active
bool alert = true;
for(int i = 0; i<motionSensors.size()-1;i++) {
if(motionSensors[i]->check()) {
//active[i]=1;
alert = false;
cout <<"halleyula" <<endl;
} else{
//active[i]=0;
}
}
if(alert & !asleep) {
sendAlert();
}
}
/*Send Alarm*/
void sendAlert(){
cout<<"Alert"<<endl;
}
/*Sets the camera*/
void checkCam(){
if(day) {
cam->setCamera(true);
} else if(anomaly) {
cam->setCamera(true);
} else {
cam->setCamera(false);
}
}
void checkAnomaly(){
if(pressureValue > 20 && pressureValue < 150) {
anomaly = true;
}
if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
//Do nothing, maybe verify if person really is sleeping
}
if(pressureValue > 200) {
asleep = true;
}
}
<commit_msg>updateSensors aangepast<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>
#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
//#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"
#include <vector>
#include <iostream>
#include <wiringPi.h> //compile with -lwiringPi
using namespace std;
vector<Sensor*> motionSensors; //Vector of the sensors
vector<Light*> lights; //Vector of the lights
vector<int> active;
PressureSensor* pressureSensor;
Camera* cam; //Pointer to the camera
Log* log;
int pressureValue;
bool asleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();
int main() {
init();
while(1) {
updateSensors();
checkAnomaly();
checkCam();
}
}
/*Init for the main*/
void init() {
wiringPiSetupGpio();
I2CCom i2c(I2CLOC); //the i2c to communicate with sensor
Light x(22);
MotionSensor s1(0xFC,i2c);
MotionSensor s2(0xBC,i2c);
MotionSensor s3(0xEC,i2c);
PressureSensor s4(0x06, i2c);
Log l1(LOG);
Camera c1;
cam = &c1;
log = &l1;
pressureSensor = &s4;
motionSensors.push_back(&s1);
motionSensors.push_back(&s2);
motionSensors.push_back(&s3);
lights.push_back(&x);
active.resize(motionSensors.size());
}
/*Updates sensors*/
void updateSensors() {
//update van elke sensor de value en de active
bool alert = true;
for(int i = 0; i<motionSensors.size()-1;i++) {
if(motionSensors[i]->check()) {
//active[i]=1;
alert = false;
cout <<"halleyula" <<endl;
} else{
//active[i]=0;
}
}
if (s4->check()) {
asleep = true;
}
if(alert & !asleep) {
sendAlert();
}
pressureValue = s4->getValue();
}
/*Send Alarm*/
void sendAlert(){
cout<<"Alert"<<endl;
}
/*Sets the camera*/
void checkCam(){
if(day) {
cam->setCamera(true);
} else if(anomaly) {
cam->setCamera(true);
} else {
cam->setCamera(false);
}
}
void checkAnomaly(){
if(pressureValue > 20 && pressureValue < 150) {
anomaly = true;
}
if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
//Do nothing, maybe verify if person really is sleeping
}
if(pressureValue > 200) {
asleep = true;
}
}
<|endoftext|>
|
<commit_before>//
// AppleGCR.cpp
// Clock Signal
//
// Created by Thomas Harte on 21/04/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "AppleGCR.hpp"
namespace {
const unsigned int five_and_three_mapping[] = {
0xab, 0xad, 0xae, 0xaf, 0xb5, 0xb6, 0xb7, 0xba,
0xbb, 0xbd, 0xbe, 0xbf, 0xd6, 0xd7, 0xda, 0xdb,
0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xed, 0xee, 0xef,
0xf5, 0xf6, 0xf7, 0xfa, 0xfb, 0xfd, 0xfe, 0xff
};
const uint8_t six_and_two_mapping[] = {
0x96, 0x97, 0x9a, 0x9b, 0x9d, 0x9e, 0x9f, 0xa6,
0xa7, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb9, 0xba, 0xbb, 0xbc,
0xbd, 0xbe, 0xbf, 0xcb, 0xcd, 0xce, 0xcf, 0xd3,
0xd6, 0xd7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde,
0xdf, 0xe5, 0xe6, 0xe7, 0xe9, 0xea, 0xeb, 0xec,
0xed, 0xee, 0xef, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6,
0xf7, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
/*!
Produces a PCM segment containing @c length sync bytes, each aligned to the beginning of
a @c bit_size -sized window.
*/
Storage::Disk::PCMSegment sync(int length, int bit_size) {
Storage::Disk::PCMSegment segment;
// Allocate sufficient storage.
segment.data.resize(static_cast<size_t>(((length * bit_size) + 7) >> 3), 0);
while(length--) {
segment.data[segment.number_of_bits >> 3] |= 0xff >> (segment.number_of_bits & 7);
if(segment.number_of_bits & 7) {
segment.data[1 + (segment.number_of_bits >> 3)] |= 0xff << (8 - (segment.number_of_bits & 7));
}
segment.number_of_bits += static_cast<unsigned int>(bit_size);
}
return segment;
}
}
using namespace Storage::Encodings;
/*void AppleGCR::encode_five_and_three_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[0] >> 3 ));
destination[1] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[0] << 2) | (source[1] >> 6) ));
destination[2] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[1] >> 1 ));
destination[3] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[1] << 4) | (source[2] >> 4) ));
destination[4] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[2] << 1) | (source[3] >> 7) ));
destination[5] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[3] >> 2 ));
destination[6] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[3] << 3) | (source[4] >> 5) ));
destination[7] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[4] ));
}*/
/*void AppleGCR::encode_six_and_two_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[0] >> 2 ));
destination[1] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[0] << 4) | (source[1] >> 4) ));
destination[2] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[1] << 2) | (source[2] >> 6) ));
destination[3] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[2] ));
}*/
Storage::Disk::PCMSegment AppleGCR::six_and_two_sync(int length) {
return sync(length, 9);
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_sync(int length) {
return sync(length, 10);
}
Storage::Disk::PCMSegment AppleGCR::header(uint8_t volume, uint8_t track, uint8_t sector) {
const uint8_t checksum = volume ^ track ^ sector;
// Apple headers are encoded using an FM-esque scheme rather than 6 and 2, or 5 and 3.
Storage::Disk::PCMSegment segment;
segment.data.resize(14);
segment.number_of_bits = 14*8;
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
#define WriteFM(index, value) \
segment.data[index+0] = static_cast<uint8_t>((value >> 1) | 0xaa); \
segment.data[index+1] = static_cast<uint8_t>(value | 0xaa); \
WriteFM(3, volume);
WriteFM(5, track);
WriteFM(7, sector);
WriteFM(9, checksum);
#undef WriteFM
segment.data[11] = epilogue[0];
segment.data[12] = epilogue[1];
segment.data[13] = epilogue[2];
return segment;
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(410 + 7);
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
// std::size_t source_pointer = 0;
// std::size_t destination_pointer = 3;
// while(source_pointer < 255) {
// encode_five_and_three_block(&segment.data[destination_pointer], &source[source_pointer]);
//
// source_pointer += 5;
// destination_pointer += 8;
// }
return segment;
}
Storage::Disk::PCMSegment AppleGCR::six_and_two_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(349);
segment.number_of_bits = static_cast<unsigned int>(segment.data.size() * 8);
// Add the prologue and epilogue.
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
segment.data[346] = epilogue[0];
segment.data[347] = epilogue[1];
segment.data[348] = epilogue[2];
// Fill in byte values: the first 86 bytes contain shuffled
// and combined copies of the bottom two bits of the sector
// contents; the 256 bytes afterwards are the remaining
// six bits.
const uint8_t bit_shuffle[] = {0, 2, 1, 3};
for(std::size_t c = 0; c < 85; ++c) {
segment.data[3 + c] =
static_cast<uint8_t>(
bit_shuffle[source[c]&3] |
(bit_shuffle[source[c + 85]&3] << 2) |
(bit_shuffle[source[c + 170]&3] << 4)
);
}
segment.data[3 + 85] = bit_shuffle[source[255]&3];
for(std::size_t c = 0; c < 256; ++c) {
segment.data[3 + 85 + c] = source[c] >> 2;
}
// Exclusive OR each byte with the one before it.
segment.data[344] = segment.data[343];
std::size_t location = 343;
while(location > 3) {
segment.data[location] ^= segment.data[location-1];
--location;
}
// Map six-bit values up to full bytes.
for(std::size_t c = 0; c < 343; ++c) {
segment.data[3 + c] = six_and_two_mapping[segment.data[3 + c]];
}
return segment;
}
<commit_msg>Corrects sync lengths.<commit_after>//
// AppleGCR.cpp
// Clock Signal
//
// Created by Thomas Harte on 21/04/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "AppleGCR.hpp"
namespace {
const unsigned int five_and_three_mapping[] = {
0xab, 0xad, 0xae, 0xaf, 0xb5, 0xb6, 0xb7, 0xba,
0xbb, 0xbd, 0xbe, 0xbf, 0xd6, 0xd7, 0xda, 0xdb,
0xdd, 0xde, 0xdf, 0xea, 0xeb, 0xed, 0xee, 0xef,
0xf5, 0xf6, 0xf7, 0xfa, 0xfb, 0xfd, 0xfe, 0xff
};
const uint8_t six_and_two_mapping[] = {
0x96, 0x97, 0x9a, 0x9b, 0x9d, 0x9e, 0x9f, 0xa6,
0xa7, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb9, 0xba, 0xbb, 0xbc,
0xbd, 0xbe, 0xbf, 0xcb, 0xcd, 0xce, 0xcf, 0xd3,
0xd6, 0xd7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde,
0xdf, 0xe5, 0xe6, 0xe7, 0xe9, 0xea, 0xeb, 0xec,
0xed, 0xee, 0xef, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6,
0xf7, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
/*!
Produces a PCM segment containing @c length sync bytes, each aligned to the beginning of
a @c bit_size -sized window.
*/
Storage::Disk::PCMSegment sync(int length, int bit_size) {
Storage::Disk::PCMSegment segment;
// Allocate sufficient storage.
segment.data.resize(static_cast<size_t>(((length * bit_size) + 7) >> 3), 0);
while(length--) {
segment.data[segment.number_of_bits >> 3] |= 0xff >> (segment.number_of_bits & 7);
if(segment.number_of_bits & 7) {
segment.data[1 + (segment.number_of_bits >> 3)] |= 0xff << (8 - (segment.number_of_bits & 7));
}
segment.number_of_bits += static_cast<unsigned int>(bit_size);
}
return segment;
}
}
using namespace Storage::Encodings;
/*void AppleGCR::encode_five_and_three_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[0] >> 3 ));
destination[1] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[0] << 2) | (source[1] >> 6) ));
destination[2] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[1] >> 1 ));
destination[3] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[1] << 4) | (source[2] >> 4) ));
destination[4] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[2] << 1) | (source[3] >> 7) ));
destination[5] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[3] >> 2 ));
destination[6] = static_cast<uint8_t>(five_and_three_encoding_for_value( (source[3] << 3) | (source[4] >> 5) ));
destination[7] = static_cast<uint8_t>(five_and_three_encoding_for_value( source[4] ));
}*/
/*void AppleGCR::encode_six_and_two_block(uint8_t *destination, uint8_t *source) {
destination[0] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[0] >> 2 ));
destination[1] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[0] << 4) | (source[1] >> 4) ));
destination[2] = static_cast<uint8_t>(six_and_two_encoding_for_value( (source[1] << 2) | (source[2] >> 6) ));
destination[3] = static_cast<uint8_t>(six_and_two_encoding_for_value( source[2] ));
}*/
Storage::Disk::PCMSegment AppleGCR::six_and_two_sync(int length) {
return sync(length, 10);
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_sync(int length) {
return sync(length, 9);
}
Storage::Disk::PCMSegment AppleGCR::header(uint8_t volume, uint8_t track, uint8_t sector) {
const uint8_t checksum = volume ^ track ^ sector;
// Apple headers are encoded using an FM-esque scheme rather than 6 and 2, or 5 and 3.
Storage::Disk::PCMSegment segment;
segment.data.resize(14);
segment.number_of_bits = 14*8;
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
#define WriteFM(index, value) \
segment.data[index+0] = static_cast<uint8_t>((value >> 1) | 0xaa); \
segment.data[index+1] = static_cast<uint8_t>(value | 0xaa); \
WriteFM(3, volume);
WriteFM(5, track);
WriteFM(7, sector);
WriteFM(9, checksum);
#undef WriteFM
segment.data[11] = epilogue[0];
segment.data[12] = epilogue[1];
segment.data[13] = epilogue[2];
return segment;
}
Storage::Disk::PCMSegment AppleGCR::five_and_three_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(410 + 7);
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
// std::size_t source_pointer = 0;
// std::size_t destination_pointer = 3;
// while(source_pointer < 255) {
// encode_five_and_three_block(&segment.data[destination_pointer], &source[source_pointer]);
//
// source_pointer += 5;
// destination_pointer += 8;
// }
return segment;
}
Storage::Disk::PCMSegment AppleGCR::six_and_two_data(const uint8_t *source) {
Storage::Disk::PCMSegment segment;
segment.data.resize(349);
segment.number_of_bits = static_cast<unsigned int>(segment.data.size() * 8);
// Add the prologue and epilogue.
segment.data[0] = header_prologue[0];
segment.data[1] = header_prologue[1];
segment.data[2] = header_prologue[2];
segment.data[346] = epilogue[0];
segment.data[347] = epilogue[1];
segment.data[348] = epilogue[2];
// Fill in byte values: the first 86 bytes contain shuffled
// and combined copies of the bottom two bits of the sector
// contents; the 256 bytes afterwards are the remaining
// six bits.
const uint8_t bit_shuffle[] = {0, 2, 1, 3};
for(std::size_t c = 0; c < 85; ++c) {
segment.data[3 + c] =
static_cast<uint8_t>(
bit_shuffle[source[c]&3] |
(bit_shuffle[source[c + 85]&3] << 2) |
(bit_shuffle[source[c + 170]&3] << 4)
);
}
segment.data[3 + 85] = bit_shuffle[source[255]&3];
for(std::size_t c = 0; c < 256; ++c) {
segment.data[3 + 85 + c] = source[c] >> 2;
}
// Exclusive OR each byte with the one before it.
segment.data[344] = segment.data[343];
std::size_t location = 343;
while(location > 3) {
segment.data[location] ^= segment.data[location-1];
--location;
}
// Map six-bit values up to full bytes.
for(std::size_t c = 0; c < 343; ++c) {
segment.data[3 + c] = six_and_two_mapping[segment.data[3 + c]];
}
return segment;
}
<|endoftext|>
|
<commit_before>// UI:
// http://qt-project.org/doc/qt-4.8/qtablewidget.html#details
//
// Model:
//
// Store:
#include "top/config.h"
#include "view/mainwindow.h"
#include "canary/model.h"
#include "dal/pq_queries.h"
#include "top/app_types.h"
#include "canary/isolation.h"
#include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QTableWidget>
#include <boost/shared_ptr.hpp>
#include <loki/ScopeGuard.h>
#include <gtest/gtest.h>
#include <boost/make_shared.hpp>
#include <actors_and_workers/concurent_queues.h>
#include <memory>
#include <cassert>
#include <iostream>
#include <thread>
using Loki::ScopeGuard;
using Loki::MakeObjGuard;
using ::isolation::ModelListenerMediatorDynPolym;
class ModelListenerMediator : public ModelListenerMediatorDynPolym {
public:
explicit ModelListenerMediator(Engine* const view) : view_(view) {
// не должно быть нулем
}
private:
void update_() {
assert(view_);
view_->redraw();
}
Engine* const view_;
};
class UIActor {
public:
typedef std::function<void()> Message;
explicit UIActor(boost::shared_ptr<models::Model> model_ptr)
: done(false), mq(100)
{ thd = std::unique_ptr<std::thread>(new std::thread( [=]{ this->Run(model_ptr); } ) ); }
~UIActor() {
Send( [&]{
done = true;
} ); ;
thd->join();
}
void Send( Message m )
{
auto r = mq.try_push( m );
}
private:
UIActor( const UIActor& ); // no copying
void operator=( const UIActor& ); // no copying
bool done; // le flag
//concurent::message_queue<Message> mq; // le queue
fix_extern_concurent::concurent_bounded_try_queue<Message> mq;
std::unique_ptr<std::thread> thd; // le thread
void Run(boost::shared_ptr<models::Model> model_ptr) {
int argc = 1;
char* argv[1] = { "none" };
QApplication app(argc, argv);
auto window = new Engine(model_ptr.get());
boost::shared_ptr<ModelListenerMediatorDynPolym> listener(new ModelListenerMediator(window));
model_ptr->set_listener(listener); // bad!
window->show();
// http://qt-project.org/doc/qt-4.8/qeventloop.html#processEvents
//app.exec(); // it's trouble for Actors usige
while( !done ) {
// ! can't sleep or wait!
Message msg;
if (mq.try_pop(msg))
msg(); // execute message
// main event loop
app.processEvents(); // hat processor!
} // note: last message sets done to true
}
};
// Actor model troubles:
// https://www.qtdeveloperdays.com/2013/sites/default/files/presentation_pdf/Qt_Event_Loop.pdf
// http://blog.bbv.ch/2012/10/03/multithreaded-programming-with-qt/
//
// http://www.christeck.de/wp/2010/10/23/the-great-qthread-mess/
//
// Why not Qt?
// http://programmers.stackexchange.com/questions/88685/why-arent-more-desktop-apps-written-with-qt
TEST(Blocked, TestApp) {
// work in DB thread
storages::ConnectionPoolPtr pool(
new pq_dal::PQConnectionsPool(models::kConnection, models::kTaskTableNameRef));
// work in UI thread
auto model_ptr = boost::shared_ptr<models::Model>(models::Model::createForOwn(pool));
auto _ = MakeObjGuard(*model_ptr, &models::Model::clear_store);
{
int argc = 1;
char* argv[1] = { "none" };
QApplication app(argc, argv);
auto window = new Engine(model_ptr.get());
boost::shared_ptr<ModelListenerMediatorDynPolym> listener(new ModelListenerMediator(window));
model_ptr->set_listener(listener); // bad!
window->show();
// http://qt-project.org/doc/qt-4.8/qeventloop.html#processEvents
//app.exec(); // it's trouble for Actors usige
while(true) {
// ! can't sleep or wait!
app.processEvents(); // hat processor!
}
}
}
// FIXME: posting from other threads
// http://qt-project.org/wiki/ThreadsEventsQObjects
TEST(Blocked, UIActorTest) {
// work in DB thread
storages::ConnectionPoolPtr pool(
new pq_dal::PQConnectionsPool(models::kConnection, models::kTaskTableNameRef));
// work in UI thread
auto model_ptr = boost::shared_ptr<models::Model>(models::Model::createForOwn(pool));
auto _ = MakeObjGuard(*model_ptr, &models::Model::clear_store);
UIActor ui(model_ptr); // dtor will call and app out
// FIXME: troubles with out appl.
while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); } // bad!
}
<commit_msg>global trouble with arch<commit_after>// UI:
// http://qt-project.org/doc/qt-4.8/qtablewidget.html#details
//
// Model:
//
// Store:
#include "top/config.h"
#include "view/mainwindow.h"
#include "canary/model.h"
#include "dal/pq_queries.h"
#include "top/app_types.h"
#include "canary/isolation.h"
#include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QTableWidget>
#include <boost/shared_ptr.hpp>
#include <loki/ScopeGuard.h>
#include <gtest/gtest.h>
#include <boost/make_shared.hpp>
#include <actors_and_workers/concurent_queues.h>
#include <memory>
#include <cassert>
#include <iostream>
#include <thread>
using Loki::ScopeGuard;
using Loki::MakeObjGuard;
using ::isolation::ModelListenerMediatorDynPolym;
class ModelListenerMediator : public ModelListenerMediatorDynPolym {
public:
explicit ModelListenerMediator(Engine* const view) : view_(view) {
// не должно быть нулем
}
private:
void update_() {
assert(view_);
view_->redraw();
}
Engine* const view_;
};
class UIActor {
public:
typedef std::function<void()> Message;
// FIXME: trouble is not non-arg ctor
explicit UIActor(boost::shared_ptr<models::Model> model_ptr)
: done(false), mq(100)
{
thd = std::unique_ptr<std::thread>(new std::thread( [=]{ this->Run(model_ptr); } ) );
}
~UIActor() {
Send( [&]{
done = true;
} ); ;
thd->join();
}
void Send( Message m )
{
auto r = mq.try_push( m );
}
private:
UIActor( const UIActor& ); // no copying
void operator=( const UIActor& ); // no copying
bool done; // le flag
//concurent::message_queue<Message> mq; // le queue
fix_extern_concurent::concurent_bounded_try_queue<Message> mq;
std::unique_ptr<std::thread> thd; // le thread
void Run(boost::shared_ptr<models::Model> model_ptr) {
int argc = 1;
char* argv[1] = { "none" };
QApplication app(argc, argv);
auto window = new Engine(model_ptr.get());
boost::shared_ptr<ModelListenerMediatorDynPolym> listener(new ModelListenerMediator(window));
model_ptr->set_listener(listener);
window->show();
// http://qt-project.org/doc/qt-4.8/qeventloop.html#processEvents
//app.exec(); // it's trouble for Actors usige
while( !done ) {
// ! can't sleep or wait!
Message msg;
if (mq.try_pop(msg))
msg(); // execute message
// main event loop
app.processEvents(); // hat processor!
} // note: last message sets done to true
}
};
// Actor model troubles:
// https://www.qtdeveloperdays.com/2013/sites/default/files/presentation_pdf/Qt_Event_Loop.pdf
// http://blog.bbv.ch/2012/10/03/multithreaded-programming-with-qt/
//
// http://www.christeck.de/wp/2010/10/23/the-great-qthread-mess/
//
// Why not Qt?
// http://programmers.stackexchange.com/questions/88685/why-arent-more-desktop-apps-written-with-qt
TEST(Blocked, TestApp) {
// work in DB thread
storages::ConnectionPoolPtr pool(
new pq_dal::PQConnectionsPool(models::kConnection, models::kTaskTableNameRef));
// work in UI thread
auto model_ptr = boost::shared_ptr<models::Model>(models::Model::createForOwn(pool));
auto _ = MakeObjGuard(*model_ptr, &models::Model::clear_store);
// FIXME: can't post to exist actor - it block it!
// May be can, but UI may be will be slow.
{
int argc = 1;
char* argv[1] = { "none" };
QApplication app(argc, argv);
auto window = new Engine(model_ptr.get());
boost::shared_ptr<ModelListenerMediatorDynPolym> listener(new ModelListenerMediator(window));
model_ptr->set_listener(listener); // bad!
window->show();
// http://qt-project.org/doc/qt-4.8/qeventloop.html#processEvents
//app.exec(); // it's trouble for Actors usige
while(true) {
// ! can't sleep or wait!
app.processEvents(); // hat processor!
}
}
}
// FIXME: posting from other threads
// http://qt-project.org/wiki/ThreadsEventsQObjects
TEST(Blocked, UIActorTest) {
// work in DB thread
storages::ConnectionPoolPtr pool(
new pq_dal::PQConnectionsPool(models::kConnection, models::kTaskTableNameRef));
// work in UI thread
auto model_ptr = boost::shared_ptr<models::Model>(models::Model::createForOwn(pool));
auto _ = MakeObjGuard(*model_ptr, &models::Model::clear_store);
UIActor ui(model_ptr); // dtor will call and app out
ui.Send([model_ptr] {
model_ptr->getCurrentModelData();
});
// FIXME: troubles with out appl.
while(true) { std::this_thread::sleep_for(std::chrono::milliseconds(50)); } // bad!
}
<|endoftext|>
|
<commit_before>/***************************************************************************
Copyright (C) 2007
by Marco Gulino <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
***************************************************************************/
#include "smslist.h"
#include <kdebug.h>
#include <qdir.h>
#include <Q3PtrList>
#include <kfiledialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include "kmobiletools_cfg.h"
#include "devicesconfig.h"
#include <QListIterator>
class SMSListPrivate {
public:
SMSListPrivate() : i_unread_phone(0), i_unread_sim(0), i_read_phone(0), i_read_sim(0),
i_sent_phone(0), i_sent_sim(0), i_unsent_phone(0), i_unsent_sim(0) {}
int i_unread_phone, i_unread_sim;
int i_read_phone, i_read_sim;
int i_sent_phone, i_sent_sim;
int i_unsent_phone, i_unsent_sim;
QString s_enginename;
};
SMSList::SMSList(const QString &enginename) : QObject(), QList<SMS*>(), d(new SMSListPrivate)
{
resetCount();
if(! enginename.isNull() ) setEngineName(enginename);
}
SMSList::~SMSList()
{
}
void SMSList::append( SMSList *sublist, bool sync)
{
if(!sublist || !sublist->size()) return;
QList<SMS*>::iterator it;
for(it=sublist->begin(); it!=sublist->end(); ++it)
{
if(sync) { if( indexOf(*it)==-1) append(*it); }
else append(*it);
++it;
}
}
/*!
\fn SMSList::find(int uid)
*/
int SMSList::find(const QString &uid) const
{
int found = 0;
QListIterator<SMS*> it( *this );
while( it.hasNext() ) {
if( it.next()->uid() == uid )
return found;
found++;
}
return -1;
}
/*!
\fn SMSList::sync (SMSList *compList)
*/
void SMSList::sync (SMSList *compList)
{
SMS *tempSMS;
// Parsing the current SMSList. If some items are not found in the new one, they'll be removed
QListIterator<SMS*> it (*this);
while( (!this->isEmpty()) && it.hasNext() )
{
tempSMS=it.next();
if( compList->find( tempSMS->uid() ) == -1 )
{
emit removed(tempSMS->uid() );
removeAll(tempSMS);
// delete tempSMS;
}
}
// Now parsing the new SMSList to find new items to add
QListIterator<SMS*> it2 (*compList);
while( it2.hasNext() )
{
tempSMS=it2.next();
if( this->find( tempSMS->uid() ) == -1 )
{
append(tempSMS);
emit added(tempSMS->uid() );
}
}
}
/// @TODO look if this is to be ported
// int SMSList::compareItems( Q3PtrCollection::Item item1, Q3PtrCollection::Item item2 )
// {
// return ( ((SMS*) item1)->uid()== ((SMS*) item2)->uid() );
// }
void SMSList::dump() const
{
SMS *tempSMS;
int i=0;
// Parsing the current SMSList. If some items are not found in the new one, they'll be removed
QListIterator<SMS*> it (*this);
while( it.hasNext() && !this->isEmpty() )
{
tempSMS=it.next();
i++;
kDebug() << "SMSList::dump(): " << QString("%1").arg(i,2) << "|" << tempSMS->uid() << "|" << tempSMS->type() << "|" << tempSMS->getText() << endl;
}
// kDebug() << "SMSList::dump(): Unread=" << i_unread << "; Read=" << i_read << "; Sent=" << i_sent << "; Unsent=" << i_unsent << endl;
}
void SMSList::calcSMSNumber() const
{
resetCount();
SMS *tempSMS;
QListIterator<SMS*> it2 (*this);
while( it2.hasNext() )
{
tempSMS=it2.next();
// kDebug() << QString("SMS Type: %1").arg(tempSMS->type() ,8,2) << endl;
switch (tempSMS->type())
{
case SMS::Unread:
if(tempSMS->slot() & SMS::SIM) d->i_unread_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_unread_phone++;
break;
case SMS::Read:
if(tempSMS->slot() & SMS::SIM) d->i_read_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_read_phone++;
break;
case SMS::Unsent:
if(tempSMS->slot() & SMS::SIM) d->i_unsent_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_unsent_phone++;
break;
case SMS::Sent:
if(tempSMS->slot() & SMS::SIM) d->i_sent_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_sent_phone++;
break;
case SMS::All:
//we shouldn't be here...
break;
}
}
}
int SMSList::count(int smsType, int memSlot) const
{
int result=0;
if( (smsType & SMS::Unread) )
{
if( memSlot & SMS::SIM ) result+= d->i_unread_sim;
if( memSlot & SMS::Phone) result+=d->i_unread_phone;
}
if( (smsType & SMS::Read) )
{
if( memSlot & SMS::SIM ) result+= d->i_read_sim;
if( memSlot & SMS::Phone) result+=d->i_read_phone;
}
if( (smsType & SMS::Unsent) )
{
if( memSlot & SMS::SIM ) result+= d->i_unsent_sim;
if( memSlot & SMS::Phone) result+=d->i_unsent_phone;
}
if( (smsType & SMS::Sent) )
{
if( memSlot & SMS::SIM ) result+= d->i_sent_sim;
if( memSlot & SMS::Phone) result+=d->i_sent_phone;
}
return result;
}
#include "smslist.moc"
/*!
\fn SMSList::saveToMailBox(const QString &engineName)
*/
void SMSList::saveToMailBox(const QString &engineName)
{
setEngineName(engineName);
saveToMailBox();
}
/*!
\fn SMSList::saveToMailBox()
*/
void SMSList::saveToMailBox() const
{
QDir savedir=(KMobileTools::DevicesConfig::prefs(engineName() ))->maildir_path();
QString dir=savedir.dirName();
savedir.cdUp();
dir=savedir.absolutePath() + QDir::separator() + '.' + dir + ".directory"
+ QDir::separator() + '.' + KMobileTools::DevicesConfig::prefs(d->s_enginename)->devicename() + ".directory";
QListIterator<SMS*> it(*this);
while( it.hasNext() )
{
it.next()->exportMD(dir);
}
}
/*!
\fn SMSList::saveToCSV(const QString &engineName)
*/
int SMSList::saveToCSV(const QString &filename) const
{
kDebug() << k_funcinfo << endl;
SMS *sms;
kdDebug() << "SMSList::saveToCSV(): saving CSV file to: " << filename << endl;
bool ok=true;
/* QListIterator<SMS*> it(*this);
while( (it.hasNext()) )
{
sms=it.next();
ok&=sms->writeToSlotCSV(filename);
}*/
for(int i=0; i<size(); i++) {
sms=at(i);
ok&=sms->writeToSlotCSV(filename);
}
return ok;
}
/*!
\fn SMSList::saveToCSV()
*/
/// @TODO Check if we can remove dialog windows out of this class, emitting insteada signal.
int SMSList::saveToCSV() const
{
QString saveFile;
saveFile = KFileDialog::getSaveFileName (QDir::homePath(), "*.csv", 0, i18n("Save file to disk"));
if ( QFile::exists(saveFile)) {
kDebug() << "SMSList::saveToCSV(): FILE ALREADY EXISTS " << endl;
int retval;
retval=KMessageBox::warningContinueCancel(NULL,
i18n("<qt>The file already exists\nOverwrite the current file?</qt>"),
"KMobileTools" );
if(retval == KMessageBox::Continue) {
QFile::remove(saveFile);
}
else {
return -1;
}
}
return saveToCSV(saveFile);
}
void SMSList::append( SMS *item )
{
QList<SMS*>::append(item);
connect(item, SIGNAL(updated()), this, SIGNAL(updated()) );
}
void SMSList::resetCount() const {
d->i_unread_phone=d->i_unread_sim=d->i_read_phone=d->i_read_sim=d->i_unsent_phone=d->i_unsent_sim=d->i_sent_phone=d->i_sent_sim=0;
}
void SMSList::setEngineName(const QString &enginename) { d->s_enginename=enginename; }
QString SMSList::engineName() const { return d->s_enginename; }
<commit_msg>Some fixes to CSV exporting.<commit_after>/***************************************************************************
Copyright (C) 2007
by Marco Gulino <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
***************************************************************************/
#include "smslist.h"
#include <kdebug.h>
#include <qdir.h>
#include <Q3PtrList>
#include <kfiledialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include "kmobiletools_cfg.h"
#include "devicesconfig.h"
#include <QListIterator>
class SMSListPrivate {
public:
SMSListPrivate() : i_unread_phone(0), i_unread_sim(0), i_read_phone(0), i_read_sim(0),
i_sent_phone(0), i_sent_sim(0), i_unsent_phone(0), i_unsent_sim(0) {}
int i_unread_phone, i_unread_sim;
int i_read_phone, i_read_sim;
int i_sent_phone, i_sent_sim;
int i_unsent_phone, i_unsent_sim;
QString s_enginename;
};
SMSList::SMSList(const QString &enginename) : QObject(), QList<SMS*>(), d(new SMSListPrivate)
{
resetCount();
if(! enginename.isNull() ) setEngineName(enginename);
}
SMSList::~SMSList()
{
}
void SMSList::append( SMSList *sublist, bool sync)
{
if(!sublist || !sublist->size()) return;
QList<SMS*>::iterator it;
for(it=sublist->begin(); it!=sublist->end(); ++it)
{
if(sync) { if( indexOf(*it)==-1) append(*it); }
else append(*it);
++it;
}
}
/*!
\fn SMSList::find(int uid)
*/
int SMSList::find(const QString &uid) const
{
int found = 0;
QListIterator<SMS*> it( *this );
while( it.hasNext() ) {
if( it.next()->uid() == uid )
return found;
found++;
}
return -1;
}
/*!
\fn SMSList::sync (SMSList *compList)
*/
void SMSList::sync (SMSList *compList)
{
SMS *tempSMS;
// Parsing the current SMSList. If some items are not found in the new one, they'll be removed
QListIterator<SMS*> it (*this);
while( (!this->isEmpty()) && it.hasNext() )
{
tempSMS=it.next();
if( compList->find( tempSMS->uid() ) == -1 )
{
emit removed(tempSMS->uid() );
removeAll(tempSMS);
// delete tempSMS;
}
}
// Now parsing the new SMSList to find new items to add
QListIterator<SMS*> it2 (*compList);
while( it2.hasNext() )
{
tempSMS=it2.next();
if( this->find( tempSMS->uid() ) == -1 )
{
append(tempSMS);
emit added(tempSMS->uid() );
}
}
}
/// @TODO look if this is to be ported
// int SMSList::compareItems( Q3PtrCollection::Item item1, Q3PtrCollection::Item item2 )
// {
// return ( ((SMS*) item1)->uid()== ((SMS*) item2)->uid() );
// }
void SMSList::dump() const
{
SMS *tempSMS;
int i=0;
// Parsing the current SMSList. If some items are not found in the new one, they'll be removed
QListIterator<SMS*> it (*this);
while( it.hasNext() && !this->isEmpty() )
{
tempSMS=it.next();
i++;
kDebug() << "SMSList::dump(): " << QString("%1").arg(i,2) << "|" << tempSMS->uid() << "|" << tempSMS->type() << "|" << tempSMS->getText() << endl;
}
// kDebug() << "SMSList::dump(): Unread=" << i_unread << "; Read=" << i_read << "; Sent=" << i_sent << "; Unsent=" << i_unsent << endl;
}
void SMSList::calcSMSNumber() const
{
resetCount();
SMS *tempSMS;
QListIterator<SMS*> it2 (*this);
while( it2.hasNext() )
{
tempSMS=it2.next();
// kDebug() << QString("SMS Type: %1").arg(tempSMS->type() ,8,2) << endl;
switch (tempSMS->type())
{
case SMS::Unread:
if(tempSMS->slot() & SMS::SIM) d->i_unread_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_unread_phone++;
break;
case SMS::Read:
if(tempSMS->slot() & SMS::SIM) d->i_read_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_read_phone++;
break;
case SMS::Unsent:
if(tempSMS->slot() & SMS::SIM) d->i_unsent_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_unsent_phone++;
break;
case SMS::Sent:
if(tempSMS->slot() & SMS::SIM) d->i_sent_sim++;
if(tempSMS->slot() & SMS::Phone) d->i_sent_phone++;
break;
case SMS::All:
//we shouldn't be here...
break;
}
}
}
int SMSList::count(int smsType, int memSlot) const
{
int result=0;
if( (smsType & SMS::Unread) )
{
if( memSlot & SMS::SIM ) result+= d->i_unread_sim;
if( memSlot & SMS::Phone) result+=d->i_unread_phone;
}
if( (smsType & SMS::Read) )
{
if( memSlot & SMS::SIM ) result+= d->i_read_sim;
if( memSlot & SMS::Phone) result+=d->i_read_phone;
}
if( (smsType & SMS::Unsent) )
{
if( memSlot & SMS::SIM ) result+= d->i_unsent_sim;
if( memSlot & SMS::Phone) result+=d->i_unsent_phone;
}
if( (smsType & SMS::Sent) )
{
if( memSlot & SMS::SIM ) result+= d->i_sent_sim;
if( memSlot & SMS::Phone) result+=d->i_sent_phone;
}
return result;
}
#include "smslist.moc"
/*!
\fn SMSList::saveToMailBox(const QString &engineName)
*/
void SMSList::saveToMailBox(const QString &engineName)
{
setEngineName(engineName);
saveToMailBox();
}
/*!
\fn SMSList::saveToMailBox()
*/
void SMSList::saveToMailBox() const
{
QDir savedir=(KMobileTools::DevicesConfig::prefs(engineName() ))->maildir_path();
QString dir=savedir.dirName();
savedir.cdUp();
dir=savedir.absolutePath() + QDir::separator() + '.' + dir + ".directory"
+ QDir::separator() + '.' + KMobileTools::DevicesConfig::prefs(d->s_enginename)->devicename() + ".directory";
QListIterator<SMS*> it(*this);
while( it.hasNext() )
{
it.next()->exportMD(dir);
}
}
/*!
\fn SMSList::saveToCSV(const QString &engineName)
*/
int SMSList::saveToCSV(const QString &filename) const
{
kDebug() << k_funcinfo << endl;
SMS *sms;
kdDebug() << "SMSList::saveToCSV(): saving CSV file to: " << filename << endl;
bool ok=true;
/* QListIterator<SMS*> it(*this);
while( (it.hasNext()) )
{
sms=it.next();
ok&=sms->writeToSlotCSV(filename);
}*/
for(int i=0; i<size(); i++) {
sms=at(i);
ok&=sms->writeToSlotCSV(filename);
}
return ok;
}
/*!
\fn SMSList::saveToCSV()
*/
/// @TODO Check if we can remove dialog windows out of this class, emitting insteada signal.
int SMSList::saveToCSV() const
{
QString saveFile;
saveFile = KFileDialog::getSaveFileName (QDir::homePath(), "*.csv", 0, i18n("Save file to disk"));
if(saveFile.isEmpty() ) return -1;
if ( QFile::exists(saveFile)) {
kDebug() << "SMSList::saveToCSV(): File already exists " << endl;
int retval;
retval=KMessageBox::warningContinueCancel(NULL,
i18n("<qt>The file already exists\nOverwrite the current file?</qt>"),
"KMobileTools" );
if(retval == KMessageBox::Continue) {
QFile::remove(saveFile);
}
else {
return -1;
}
}
return saveToCSV(saveFile);
}
void SMSList::append( SMS *item )
{
QList<SMS*>::append(item);
connect(item, SIGNAL(updated()), this, SIGNAL(updated()) );
}
void SMSList::resetCount() const {
d->i_unread_phone=d->i_unread_sim=d->i_read_phone=d->i_read_sim=d->i_unsent_phone=d->i_unsent_sim=d->i_sent_phone=d->i_sent_sim=0;
}
void SMSList::setEngineName(const QString &enginename) { d->s_enginename=enginename; }
QString SMSList::engineName() const { return d->s_enginename; }
<|endoftext|>
|
<commit_before>#include <bitbots_ros_control/wolfgang_hardware_interface.h>
#include <bitbots_ros_control/utils.h>
namespace bitbots_ros_control {
/**
* This class provides a combination of multiple hardware interfaces to construct a complete Wolfgang robot.
* It is similar to a CombinedRobotHw class as specified in ros_control, but it is changed a bit to make sharing of
* a common bus driver over multiple hardware interfaces possible.
*/
WolfgangHardwareInterface::WolfgangHardwareInterface(ros::NodeHandle& nh){
_speak_pub = nh.advertise<humanoid_league_msgs::Speak>("/speak", 1);
// load parameters
ROS_INFO_STREAM("Loading parameters from namespace " << nh.getNamespace());
nh.getParam("only_imu", _onlyImu);
if(_onlyImu) ROS_WARN("Starting in only IMU mode");
nh.getParam("only_pressure", _onlyPressure);
if(_onlyPressure) ROS_WARN("starting in only pressure sensor mode");
if(_onlyPressure && _onlyImu) {
ROS_ERROR("only_imu AND only_pressure was set to true");
exit(1);
}
// init bus driver
std::string port_name;
nh.getParam("port_info/port_name", port_name);
int baudrate;
nh.getParam("port_info/baudrate", baudrate);
auto driver = std::make_shared<DynamixelDriver>();
if(!driver->init(port_name.c_str(), uint32_t(baudrate))){
ROS_ERROR("Error opening serial port %s", port_name.c_str());
speak_error(_speak_pub, "Error opening serial port");
sleep(1);
exit(1);
}
float protocol_version;
nh.getParam("port_info/protocol_version", protocol_version);
driver->setPacketHandler(protocol_version);
_servos = DynamixelServoHardwareInterface(driver);
_imu = ImuHardwareInterface(driver);
_left_foot = BitFootHardwareInterface(driver, 101, "/foot_pressure_left/raw");
_right_foot = BitFootHardwareInterface(driver, 102, "/foot_pressure_right/raw");
_buttons = ButtonHardwareInterface(driver);
// set the dynamic reconfigure and load standard params for servo interface
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig> server;
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig>::CallbackType f;
f = boost::bind(&bitbots_ros_control::DynamixelServoHardwareInterface::reconf_callback,&_servos, _1, _2);
server.setCallback(f);
}
bool WolfgangHardwareInterface::init(ros::NodeHandle& root_nh){
bool success = true;
if(_onlyImu) {
_imu.setParent(this);
success &= _imu.init(root_nh);
}else if(_onlyPressure){
success &= _left_foot.init(root_nh);
success &= _right_foot.init(root_nh);
}else {
/* Hardware interfaces must be registered at the main RobotHW class.
* Therefore, a pointer to this class is passed down to the RobotHW classes
* registering further interfaces */
_servos.setParent(this);
_imu.setParent(this);
success &= _servos.init(root_nh);
success &= _imu.init(root_nh);
success &= _left_foot.init(root_nh);
success &= _right_foot.init(root_nh);
success &= _buttons.init(root_nh);
}
if(success) {
speak_error(_speak_pub, "ros control startup successful");
}else{
speak_error(_speak_pub, "error starting ros control");
}
return success;
}
bool WolfgangHardwareInterface::read()
{
bool success = true;
if(_onlyImu){
success &= _imu.read();
}else if(_onlyPressure){
success &= _left_foot.read();
success &= _right_foot.read();
}else{
success &= _servos.read();
success &= _imu.read();
success &= _left_foot.read();
success &= _right_foot.read();
success &= _buttons.read();
}
return success;
}
void WolfgangHardwareInterface::write()
{
if(!_onlyImu && !_onlyPressure) {
_servos.write();
}
}
}
<commit_msg>ros_control: correct foot sensor ids<commit_after>#include <bitbots_ros_control/wolfgang_hardware_interface.h>
#include <bitbots_ros_control/utils.h>
namespace bitbots_ros_control {
/**
* This class provides a combination of multiple hardware interfaces to construct a complete Wolfgang robot.
* It is similar to a CombinedRobotHw class as specified in ros_control, but it is changed a bit to make sharing of
* a common bus driver over multiple hardware interfaces possible.
*/
WolfgangHardwareInterface::WolfgangHardwareInterface(ros::NodeHandle& nh){
_speak_pub = nh.advertise<humanoid_league_msgs::Speak>("/speak", 1);
// load parameters
ROS_INFO_STREAM("Loading parameters from namespace " << nh.getNamespace());
nh.getParam("only_imu", _onlyImu);
if(_onlyImu) ROS_WARN("Starting in only IMU mode");
nh.getParam("only_pressure", _onlyPressure);
if(_onlyPressure) ROS_WARN("starting in only pressure sensor mode");
if(_onlyPressure && _onlyImu) {
ROS_ERROR("only_imu AND only_pressure was set to true");
exit(1);
}
// init bus driver
std::string port_name;
nh.getParam("port_info/port_name", port_name);
int baudrate;
nh.getParam("port_info/baudrate", baudrate);
auto driver = std::make_shared<DynamixelDriver>();
if(!driver->init(port_name.c_str(), uint32_t(baudrate))){
ROS_ERROR("Error opening serial port %s", port_name.c_str());
speak_error(_speak_pub, "Error opening serial port");
sleep(1);
exit(1);
}
float protocol_version;
nh.getParam("port_info/protocol_version", protocol_version);
driver->setPacketHandler(protocol_version);
_servos = DynamixelServoHardwareInterface(driver);
_imu = ImuHardwareInterface(driver);
_left_foot = BitFootHardwareInterface(driver, 102, "/foot_pressure_left/raw");
_right_foot = BitFootHardwareInterface(driver, 101, "/foot_pressure_right/raw");
_buttons = ButtonHardwareInterface(driver);
// set the dynamic reconfigure and load standard params for servo interface
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig> server;
dynamic_reconfigure::Server<bitbots_ros_control::dynamixel_servo_hardware_interface_paramsConfig>::CallbackType f;
f = boost::bind(&bitbots_ros_control::DynamixelServoHardwareInterface::reconf_callback,&_servos, _1, _2);
server.setCallback(f);
}
bool WolfgangHardwareInterface::init(ros::NodeHandle& root_nh){
bool success = true;
if(_onlyImu) {
_imu.setParent(this);
success &= _imu.init(root_nh);
}else if(_onlyPressure){
success &= _left_foot.init(root_nh);
success &= _right_foot.init(root_nh);
}else {
/* Hardware interfaces must be registered at the main RobotHW class.
* Therefore, a pointer to this class is passed down to the RobotHW classes
* registering further interfaces */
_servos.setParent(this);
_imu.setParent(this);
success &= _servos.init(root_nh);
success &= _imu.init(root_nh);
success &= _left_foot.init(root_nh);
success &= _right_foot.init(root_nh);
success &= _buttons.init(root_nh);
}
if(success) {
speak_error(_speak_pub, "ros control startup successful");
}else{
speak_error(_speak_pub, "error starting ros control");
}
return success;
}
bool WolfgangHardwareInterface::read()
{
bool success = true;
if(_onlyImu){
success &= _imu.read();
}else if(_onlyPressure){
success &= _left_foot.read();
success &= _right_foot.read();
}else{
success &= _servos.read();
success &= _imu.read();
success &= _left_foot.read();
success &= _right_foot.read();
success &= _buttons.read();
}
return success;
}
void WolfgangHardwareInterface::write()
{
if(!_onlyImu && !_onlyPressure) {
_servos.write();
}
}
}
<|endoftext|>
|
<commit_before>AliAnalysisTask *AddTask_Helium3Pi(TString name="name"){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_Helium3Pi", "No analysis manager found.");
return 0;
}
//========= Add task to the ANALYSIS manager =====
AliAnalysisTaskHelium3PiAOD *taskHelium3Pi = new AliAnalysisTaskHelium3PiAOD(name);
mgr->AddTask(taskHelium3Pi);
//================================================
// data containers
//================================================
// find input container
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
TString outputFileName = AliAnalysisManager::GetCommonFileName();
//AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Helium3Pi_tree", TTree::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
//AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Helium3Pi_tree", TTree::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("clisthistHyper", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("treeHyper", TTree::Class(),AliAnalysisManager::kOutputContainer,outputFileName);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("treeHelium" , TTree::Class(),AliAnalysisManager::kOutputContainer,outputFileName);
// connect containers
mgr->ConnectInput (taskHelium3Pi, 0, cinput );
mgr->ConnectOutput (taskHelium3Pi, 1, coutput1);
mgr->ConnectOutput (taskHelium3Pi, 2, coutput2);
mgr->ConnectOutput (taskHelium3Pi, 3, coutput3);
return taskHelium3Pi;
}
<commit_msg>Fixing a typo<commit_after>AliAnalysisTask *AddTask_Helium3PiAOD(TString name="name"){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_Helium3Pi", "No analysis manager found.");
return 0;
}
//========= Add task to the ANALYSIS manager =====
AliAnalysisTaskHelium3PiAOD *taskHelium3Pi = new AliAnalysisTaskHelium3PiAOD(name);
mgr->AddTask(taskHelium3Pi);
//================================================
// data containers
//================================================
// find input container
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
TString outputFileName = AliAnalysisManager::GetCommonFileName();
//AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Helium3Pi_tree", TTree::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
//AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Helium3Pi_tree", TTree::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("clisthistHyper", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);
AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("treeHyper", TTree::Class(),AliAnalysisManager::kOutputContainer,outputFileName);
AliAnalysisDataContainer *coutput3 = mgr->CreateContainer("treeHelium" , TTree::Class(),AliAnalysisManager::kOutputContainer,outputFileName);
// connect containers
mgr->ConnectInput (taskHelium3Pi, 0, cinput );
mgr->ConnectOutput (taskHelium3Pi, 1, coutput1);
mgr->ConnectOutput (taskHelium3Pi, 2, coutput2);
mgr->ConnectOutput (taskHelium3Pi, 3, coutput3);
return taskHelium3Pi;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkConvertPixelBuffer.txx"
#include "itkDICOMImageIO2.h"
#include "itkDICOMImageIO2Factory.h"
#include "itkDefaultConvertPixelTraits.h"
#include "itkDicomImageIO.h"
#include "itkDicomImageIOFactory.h"
#include "itkGiplImageIO.h"
#include "itkGiplImageIOFactory.h"
#include "itkImageFileReader.txx"
#include "itkImageFileWriter.txx"
#include "itkImageIOBase.h"
#include "itkImageIOFactory.h"
#include "itkImageIORegion.h"
#include "itkImageWriter.txx"
#include "itkMetaImageIO.h"
#include "itkMetaImageIOFactory.h"
#include "itkPNGImageIO.h"
#include "itkPNGImageIOFactory.h"
#include "itkRawImageIO.txx"
#include "itkRawImageWriter.txx"
#include "itkVOLImageIO.h"
#include "itkVOLImageIOFactory.h"
#include "itkVTKImageIO.h"
#include "itkVTKImageIOFactory.h"
#include "itkWriter.h"
int main ( int , char* )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAnalyzeImageIO.h"
#include "itkAnalyzeImageIOFactory.h"
#include "itkConvertPixelBuffer.txx"
#include "itkDICOMImageIO2.h"
#include "itkDICOMImageIO2Factory.h"
#include "itkDefaultConvertPixelTraits.h"
#include "itkDicomImageIO.h"
#include "itkDicomImageIOFactory.h"
#include "itkGiplImageIO.h"
#include "itkGiplImageIOFactory.h"
#include "itkImageFileReader.txx"
#include "itkImageFileWriter.txx"
#include "itkImageIOBase.h"
#include "itkImageIOFactory.h"
#include "itkImageIORegion.h"
#include "itkImageWriter.txx"
#include "itkMetaImageIO.h"
#include "itkMetaImageIOFactory.h"
#include "itkPNGImageIO.h"
#include "itkPNGImageIOFactory.h"
#include "itkRawImageIO.txx"
#include "itkRawImageWriter.txx"
#include "itkVOLImageIO.h"
#include "itkVOLImageIOFactory.h"
#include "itkVTKImageIO.h"
#include "itkVTKImageIOFactory.h"
#include "itkWriter.h"
int main ( int , char* )
{
return 0;
}
<|endoftext|>
|
<commit_before>/*
* DBriefDescriptorExtractor.cpp
*
* Created on: Aug 22, 2013
* Author: andresf
*/
#include <DBriefDescriptorExtractor.h>
#include <iostream>
#include <string>
namespace cv {
void DBrief(const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors,
const int& size, const int& type) {
// Converting color image to grayscale
Mat grayImage = image;
if (image.type() != CV_8U)
cvtColor(image, grayImage, COLOR_BGR2GRAY);
// DBrief object which contains methods describing keypoints with dbrief descriptors.
CVLAB::Dbrief dbrief;
IplImage ipl_grayImage = grayImage;
vector<bitset<CVLAB::DESC_LEN> > descs;
dbrief.getDbriefDescriptors(descs, keypoints, &ipl_grayImage);
descriptors.create((int) keypoints.size(), size, type);
// Initializing matrix with zeros
std::fill_n(descriptors.data, descriptors.rows * descriptors.cols, 0);
for (int i = 0; i < (int) descs.size(); i++) {
bitset<CVLAB::DESC_LEN> desc = descs[i];
//printf("String formatted: %s\n", desc.to_string<char, char_traits<char>, allocator<char> >().c_str());
// Doing a reverse loop because the most significant on a bitset is the last element
// e.g. 1100 is stored as 0011
for (int j = (int) desc.size() - 1; j >= 0; j--) {
// Incrementally composing descriptor by
// splitting the 32 length bitset in chunks of 8 bits (1 byte)
// and converting it into its uint representation
descriptors.at<unsigned char>(i, descriptors.cols - 1 - (int) j / 8) +=
(desc.test(j) << (j % 8));
}
}
}
DBriefDescriptorExtractor::DBriefDescriptorExtractor() {
;
}
DBriefDescriptorExtractor::~DBriefDescriptorExtractor() {
;
}
int DBriefDescriptorExtractor::descriptorSize() const {
// D-Brief descriptor has length 32 bits or 4 Bytes
return CVLAB::DESC_LEN / 8;
}
int DBriefDescriptorExtractor::descriptorType() const {
return CV_8U;
}
void DBriefDescriptorExtractor::computeImpl(const Mat& image,
std::vector<KeyPoint>& keypoints, Mat& descriptors) const {
KeyPointsFilter::runByImageBorder(keypoints, image.size(),
CVLAB::IMAGE_PADDING_TOP);
DBrief(image, keypoints, descriptors, this->descriptorSize(),
this->descriptorType());
}
} /* namespace cv */
<commit_msg>Fixed comment.<commit_after>/*
* DBriefDescriptorExtractor.cpp
*
* Created on: Aug 22, 2013
* Author: andresf
*/
#include <DBriefDescriptorExtractor.h>
#include <iostream>
#include <string>
namespace cv {
void DBrief(const Mat& image, vector<KeyPoint>& keypoints, Mat& descriptors,
const int& size, const int& type) {
// Converting color image to grayscale
Mat grayImage = image;
if (image.type() != CV_8U)
cvtColor(image, grayImage, COLOR_BGR2GRAY);
// DBrief object which contains methods describing keypoints with dbrief descriptors.
CVLAB::Dbrief dbrief;
IplImage ipl_grayImage = grayImage;
vector<bitset<CVLAB::DESC_LEN> > descs;
dbrief.getDbriefDescriptors(descs, keypoints, &ipl_grayImage);
descriptors.create((int) keypoints.size(), size, type);
// Initializing matrix with zeros
std::fill_n(descriptors.data, descriptors.rows * descriptors.cols, 0);
for (int i = 0; i < (int) descs.size(); i++) {
bitset<CVLAB::DESC_LEN> desc = descs[i];
//printf("String formatted: %s\n", desc.to_string<char, char_traits<char>, allocator<char> >().c_str());
// Doing a reverse loop because the most significant bit on a bitset is the last element
// e.g. 1100 is stored as 0011
for (int j = (int) desc.size() - 1; j >= 0; j--) {
// Incrementally composing descriptor by
// splitting the 32 length bitset in chunks of 8 bits (1 byte)
// and converting it into its uint representation
descriptors.at<unsigned char>(i, descriptors.cols - 1 - (int) j / 8) +=
(desc.test(j) << (j % 8));
}
}
}
DBriefDescriptorExtractor::DBriefDescriptorExtractor() {
;
}
DBriefDescriptorExtractor::~DBriefDescriptorExtractor() {
;
}
int DBriefDescriptorExtractor::descriptorSize() const {
// D-Brief descriptor has length 32 bits or 4 Bytes
return CVLAB::DESC_LEN / 8;
}
int DBriefDescriptorExtractor::descriptorType() const {
return CV_8U;
}
void DBriefDescriptorExtractor::computeImpl(const Mat& image,
std::vector<KeyPoint>& keypoints, Mat& descriptors) const {
KeyPointsFilter::runByImageBorder(keypoints, image.size(),
CVLAB::IMAGE_PADDING_TOP);
DBrief(image, keypoints, descriptors, this->descriptorSize(),
this->descriptorType());
}
} /* namespace cv */
<|endoftext|>
|
<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/ReturnHandTask.hpp>
namespace RosettaStone::SimpleTasks
{
ReturnHandTask::ReturnHandTask(EntityType entityType) : ITask(entityType)
{
// Do nothing
}
TaskID ReturnHandTask::GetTaskID() const
{
return TaskID::RETURN_HAND;
}
TaskStatus ReturnHandTask::Impl(Player& player)
{
auto entities =
IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
for (auto& entity : entities)
{
Generic::RemoveMinionFromField(m_target->GetOwner(),
dynamic_cast<Minion*>(entity));
entity->Reset();
Generic::AddCardToHand(m_target->GetOwner(), entity);
}
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::SimpleTasks
<commit_msg>fix: Correct nullptr problem (change 'm_target' to 'entity')<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/ReturnHandTask.hpp>
namespace RosettaStone::SimpleTasks
{
ReturnHandTask::ReturnHandTask(EntityType entityType) : ITask(entityType)
{
// Do nothing
}
TaskID ReturnHandTask::GetTaskID() const
{
return TaskID::RETURN_HAND;
}
TaskStatus ReturnHandTask::Impl(Player& player)
{
auto entities =
IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
for (auto& entity : entities)
{
Generic::RemoveMinionFromField(entity->GetOwner(),
dynamic_cast<Minion*>(entity));
entity->Reset();
Generic::AddCardToHand(entity->GetOwner(), entity);
}
return TaskStatus::COMPLETE;
}
} // namespace RosettaStone::SimpleTasks
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 Muhammad Tayyab Akram
*
* 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.
*/
extern "C" {
#include <Headers/SBBase.h>
#include <Headers/SBConfig.h>
#include <Source/SBScriptLookup.h>
}
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <string>
#include <Parser/PropertyValueAliases.h>
#include <Parser/Scripts.h>
#include "Utilities/Convert.h"
#include "Utilities/Unicode.h"
#include "Configuration.h"
#include "ScriptLookupTester.h"
using namespace std;
using namespace SheenBidi::Parser;
using namespace SheenBidi::Tester;
using namespace SheenBidi::Tester::Utilities;
ScriptLookupTester::ScriptLookupTester(const Parser::Scripts &scripts, const Parser::PropertyValueAliases &propertyValueAliases) :
m_scripts(scripts),
m_propertyValueAliases(propertyValueAliases)
{
}
void ScriptLookupTester::test() {
#ifdef SB_CONFIG_UNITY
cout << "Cannot run script tester in unity mode." << endl;
#else
cout << "Running script tester." << endl;
size_t failCounter = 0;
for (uint32_t codePoint = 0; codePoint <= Unicode::MAX_CODE_POINT; codePoint++) {
const string &uniScript = m_scripts.scriptForCodePoint(codePoint);
const string &expScript = m_propertyValueAliases.abbreviationForScript(uniScript);
SBScript valScript = SBScriptDetermine(codePoint);
const string &genScript = Convert::scriptToString(valScript);
if (expScript != genScript) {
if (Configuration::DISPLAY_ERROR_DETAILS) {
cout << "Invalid script found: " << endl
<< " Code Point: " << codePoint << endl
<< " Expected Script: " << expScript << endl
<< " Generated Script: " << genScript << endl;
}
failCounter++;
}
}
cout << failCounter << " error/s." << endl;
cout << endl;
#endif
}
<commit_msg>[test] Minor typo fix in script lookup tester...<commit_after>/*
* Copyright (C) 2018 Muhammad Tayyab Akram
*
* 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.
*/
extern "C" {
#include <Headers/SBBase.h>
#include <Headers/SBConfig.h>
#include <Source/SBScriptLookup.h>
}
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <string>
#include <Parser/PropertyValueAliases.h>
#include <Parser/Scripts.h>
#include "Utilities/Convert.h"
#include "Utilities/Unicode.h"
#include "Configuration.h"
#include "ScriptLookupTester.h"
using namespace std;
using namespace SheenBidi::Parser;
using namespace SheenBidi::Tester;
using namespace SheenBidi::Tester::Utilities;
ScriptLookupTester::ScriptLookupTester(const Parser::Scripts &scripts, const Parser::PropertyValueAliases &propertyValueAliases) :
m_scripts(scripts),
m_propertyValueAliases(propertyValueAliases)
{
}
void ScriptLookupTester::test() {
#ifdef SB_CONFIG_UNITY
cout << "Cannot run script lookup tester in unity mode." << endl;
#else
cout << "Running script lookup tester." << endl;
size_t failCounter = 0;
for (uint32_t codePoint = 0; codePoint <= Unicode::MAX_CODE_POINT; codePoint++) {
const string &uniScript = m_scripts.scriptForCodePoint(codePoint);
const string &expScript = m_propertyValueAliases.abbreviationForScript(uniScript);
SBScript valScript = SBScriptDetermine(codePoint);
const string &genScript = Convert::scriptToString(valScript);
if (expScript != genScript) {
if (Configuration::DISPLAY_ERROR_DETAILS) {
cout << "Invalid script found: " << endl
<< " Code Point: " << codePoint << endl
<< " Expected Script: " << expScript << endl
<< " Generated Script: " << genScript << endl;
}
failCounter++;
}
}
cout << failCounter << " error/s." << endl;
cout << endl;
#endif
}
<|endoftext|>
|
<commit_before>//===-- ExternalMethods.cpp - Implement External Methods ------------------===//
//
// This file contains both code to deal with invoking "external" methods, but
// also contains code that implements "exported" external methods.
//
// External methods in LLI are implemented by dlopen'ing the lli executable and
// using dlsym to look op the methods that we want to invoke. If a method is
// found, then the arguments are mangled and passed in to the function call.
//
//===----------------------------------------------------------------------===//
#include "Interpreter.h"
#include "llvm/DerivedTypes.h"
#include <map>
#include <dlfcn.h>
#include <link.h>
#include <math.h>
typedef GenericValue (*ExFunc)(MethodType *, const vector<GenericValue> &);
static map<const Method *, ExFunc> Functions;
static Interpreter *TheInterpreter;
// getCurrentExecutablePath() - Return the directory that the lli executable
// lives in.
//
string Interpreter::getCurrentExecutablePath() const {
Dl_info Info;
if (dladdr(&TheInterpreter, &Info) == 0) return "";
string LinkAddr(Info.dli_fname);
unsigned SlashPos = LinkAddr.rfind('/');
if (SlashPos != string::npos)
LinkAddr.resize(SlashPos); // Trim the executable name off...
return LinkAddr;
}
static char getTypeID(const Type *Ty) {
switch (Ty->getPrimitiveID()) {
case Type::VoidTyID: return 'V';
case Type::BoolTyID: return 'o';
case Type::UByteTyID: return 'B';
case Type::SByteTyID: return 'b';
case Type::UShortTyID: return 'S';
case Type::ShortTyID: return 's';
case Type::UIntTyID: return 'I';
case Type::IntTyID: return 'i';
case Type::ULongTyID: return 'L';
case Type::LongTyID: return 'l';
case Type::FloatTyID: return 'F';
case Type::DoubleTyID: return 'D';
case Type::PointerTyID: return 'P';
case Type::MethodTyID: return 'M';
case Type::StructTyID: return 'T';
case Type::ArrayTyID: return 'A';
case Type::OpaqueTyID: return 'O';
default: return 'U';
}
}
static ExFunc lookupMethod(const Method *M) {
// Function not found, look it up... start by figuring out what the
// composite function name should be.
string ExtName = "lle_";
const MethodType *MT = M->getMethodType();
for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
ExtName += getTypeID(Ty);
ExtName += "_" + M->getName();
//cout << "Tried: '" << ExtName << "'\n";
ExFunc FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
if (FnPtr == 0) // Try calling a generic function... if it exists...
FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
if (FnPtr != 0)
Functions.insert(make_pair(M, FnPtr)); // Cache for later
return FnPtr;
}
void Interpreter::callExternalMethod(Method *M,
const vector<GenericValue> &ArgVals) {
TheInterpreter = this;
// Do a lookup to see if the method is in our cache... this should just be a
// defered annotation!
map<const Method *, ExFunc>::iterator FI = Functions.find(M);
ExFunc Fn = (FI == Functions.end()) ? lookupMethod(M) : FI->second;
if (Fn == 0) {
cout << "Tried to execute an unknown external method: "
<< M->getType()->getDescription() << " " << M->getName() << endl;
return;
}
// TODO: FIXME when types are not const!
GenericValue Result = Fn(const_cast<MethodType*>(M->getMethodType()),ArgVals);
// Copy the result back into the result variable if we are not returning void.
if (M->getReturnType() != Type::VoidTy) {
CallInst *Caller = ECStack.back().Caller;
if (Caller) {
} else {
// print it.
}
}
}
//===----------------------------------------------------------------------===//
// Methods "exported" to the running application...
//
extern "C" { // Don't add C++ manglings to llvm mangling :)
// Implement void printstr([ubyte {x N}] *)
GenericValue lle_VP_printstr(MethodType *M, const vector<GenericValue> &ArgVal){
assert(ArgVal.size() == 1 && "printstr only takes one argument!");
cout << (char*)ArgVal[0].PointerVal;
return GenericValue();
}
// Implement 'void print(X)' for every type...
GenericValue lle_X_print(MethodType *M, const vector<GenericValue> &ArgVals) {
assert(ArgVals.size() == 1 && "generic print only takes one argument!");
Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
return GenericValue();
}
// Implement 'void printVal(X)' for every type...
GenericValue lle_X_printVal(MethodType *M, const vector<GenericValue> &ArgVal) {
assert(ArgVal.size() == 1 && "generic print only takes one argument!");
// Specialize print([ubyte {x N} ] *) and print(sbyte *)
if (PointerType *PTy = dyn_cast<PointerType>(M->getParamTypes()[0].get()))
if (PTy->getValueType() == Type::SByteTy ||
isa<ArrayType>(PTy->getValueType())) {
return lle_VP_printstr(M, ArgVal);
}
Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
return GenericValue();
}
// Implement 'void printString(X)'
// Argument must be [ubyte {x N} ] * or sbyte *
GenericValue lle_X_printString(MethodType *M, const vector<GenericValue> &ArgVal) {
assert(ArgVal.size() == 1 && "generic print only takes one argument!");
return lle_VP_printstr(M, ArgVal);
}
// Implement 'void print<TYPE>(X)' for each primitive type or pointer type
#define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
GenericValue lle_X_print##TYPENAME(MethodType *M,\
const vector<GenericValue> &ArgVal) {\
assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::##TYPEID);\
Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
return GenericValue();\
}
PRINT_TYPE_FUNC(Byte, SByteTyID)
PRINT_TYPE_FUNC(UByte, UByteTyID)
PRINT_TYPE_FUNC(Short, ShortTyID)
PRINT_TYPE_FUNC(UShort, UShortTyID)
PRINT_TYPE_FUNC(Int, IntTyID)
PRINT_TYPE_FUNC(UInt, UIntTyID)
PRINT_TYPE_FUNC(Long, LongTyID)
PRINT_TYPE_FUNC(ULong, ULongTyID)
PRINT_TYPE_FUNC(Float, FloatTyID)
PRINT_TYPE_FUNC(Double, DoubleTyID)
PRINT_TYPE_FUNC(Pointer, PointerTyID)
// void "putchar"(sbyte)
GenericValue lle_Vb_putchar(MethodType *M, const vector<GenericValue> &Args) {
cout << Args[0].SByteVal;
return GenericValue();
}
// int "putchar"(int)
GenericValue lle_ii_putchar(MethodType *M, const vector<GenericValue> &Args) {
cout << ((char)Args[0].IntVal) << flush;
return Args[0];
}
// void "putchar"(ubyte)
GenericValue lle_VB_putchar(MethodType *M, const vector<GenericValue> &Args) {
cout << Args[0].SByteVal << flush;
return Args[0];
}
// void "__main"()
GenericValue lle_V___main(MethodType *M, const vector<GenericValue> &Args) {
return GenericValue();
}
// void "exit"(int)
GenericValue lle_Vi_exit(MethodType *M, const vector<GenericValue> &Args) {
TheInterpreter->exitCalled(Args[0]);
return GenericValue();
}
// void *malloc(uint)
GenericValue lle_PI_malloc(MethodType *M, const vector<GenericValue> &Args) {
GenericValue GV;
GV.LongVal = (uint64_t)malloc(Args[0].UIntVal);
return GV;
}
// void free(void *)
GenericValue lle_VP_free(MethodType *M, const vector<GenericValue> &Args) {
free((void*)Args[0].LongVal);
return GenericValue();
}
// double pow(double, double)
GenericValue lle_DDD_pow(MethodType *M, const vector<GenericValue> &Args) {
GenericValue GV;
GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
return GV;
}
// int printf(sbyte *, ...) - a very rough implementation to make output useful.
GenericValue lle_iP_printf(MethodType *M, const vector<GenericValue> &Args) {
const char *FmtStr = (const char *)Args[0].PointerVal;
unsigned ArgNo = 1;
// printf should return # chars printed. This is completely incorrect, but
// close enough for now.
GenericValue GV; GV.IntVal = strlen(FmtStr);
while (1) {
switch (*FmtStr) {
case 0: return GV; // Null terminator...
default: // Normal nonspecial character
cout << *FmtStr++;
break;
case '\\': { // Handle escape codes
char Buffer[3];
Buffer[0] = *FmtStr++;
Buffer[1] = *FmtStr++;
Buffer[2] = 0;
cout << Buffer;
break;
}
case '%': { // Handle format specifiers
bool isLong = false;
++FmtStr;
if (*FmtStr == 'l') {
isLong = true;
FmtStr++;
}
switch (*FmtStr) {
case '%': cout << *FmtStr; break; // %%
case 'd': // %d %i
case 'i': cout << Args[ArgNo++].IntVal; break;
case 'u': cout << Args[ArgNo++].UIntVal; break; // %u
case 'o': cout << oct << Args[ArgNo++].UIntVal << dec; break; // %o
case 'x':
case 'X': cout << hex << Args[ArgNo++].UIntVal << dec; break; // %x %X
case 'e': case 'E': case 'g': case 'G': // %[eEgG]
cout /*<< std::scientific*/ << Args[ArgNo++].DoubleVal
/*<< std::fixed*/; break;
case 'f': cout << Args[ArgNo++].DoubleVal; break; // %f
case 'c': cout << Args[ArgNo++].UByteVal; break; // %c
case 's': cout << (char*)Args[ArgNo++].PointerVal; break; // %s
default: cout << "<unknown printf code '" << *FmtStr << "'!>";
ArgNo++; break;
}
++FmtStr;
break;
}
}
}
}
} // End extern "C"
<commit_msg>Implement a gross function name map that must be used when linking statically This is for use with purify<commit_after>//===-- ExternalMethods.cpp - Implement External Methods ------------------===//
//
// This file contains both code to deal with invoking "external" methods, but
// also contains code that implements "exported" external methods.
//
// External methods in LLI are implemented by dlopen'ing the lli executable and
// using dlsym to look op the methods that we want to invoke. If a method is
// found, then the arguments are mangled and passed in to the function call.
//
//===----------------------------------------------------------------------===//
#include "Interpreter.h"
#include "llvm/DerivedTypes.h"
#include <map>
#include <dlfcn.h>
#include <link.h>
#include <math.h>
typedef GenericValue (*ExFunc)(MethodType *, const vector<GenericValue> &);
static map<const Method *, ExFunc> Functions;
static map<string, ExFunc> FuncNames;
static Interpreter *TheInterpreter;
// getCurrentExecutablePath() - Return the directory that the lli executable
// lives in.
//
string Interpreter::getCurrentExecutablePath() const {
Dl_info Info;
if (dladdr(&TheInterpreter, &Info) == 0) return "";
string LinkAddr(Info.dli_fname);
unsigned SlashPos = LinkAddr.rfind('/');
if (SlashPos != string::npos)
LinkAddr.resize(SlashPos); // Trim the executable name off...
return LinkAddr;
}
static char getTypeID(const Type *Ty) {
switch (Ty->getPrimitiveID()) {
case Type::VoidTyID: return 'V';
case Type::BoolTyID: return 'o';
case Type::UByteTyID: return 'B';
case Type::SByteTyID: return 'b';
case Type::UShortTyID: return 'S';
case Type::ShortTyID: return 's';
case Type::UIntTyID: return 'I';
case Type::IntTyID: return 'i';
case Type::ULongTyID: return 'L';
case Type::LongTyID: return 'l';
case Type::FloatTyID: return 'F';
case Type::DoubleTyID: return 'D';
case Type::PointerTyID: return 'P';
case Type::MethodTyID: return 'M';
case Type::StructTyID: return 'T';
case Type::ArrayTyID: return 'A';
case Type::OpaqueTyID: return 'O';
default: return 'U';
}
}
static ExFunc lookupMethod(const Method *M) {
// Function not found, look it up... start by figuring out what the
// composite function name should be.
string ExtName = "lle_";
const MethodType *MT = M->getMethodType();
for (unsigned i = 0; const Type *Ty = MT->getContainedType(i); ++i)
ExtName += getTypeID(Ty);
ExtName += "_" + M->getName();
//cout << "Tried: '" << ExtName << "'\n";
ExFunc FnPtr = FuncNames[ExtName];
if (FnPtr == 0)
FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ExtName.c_str());
if (FnPtr == 0)
FnPtr = FuncNames["lle_X_"+M->getName()];
if (FnPtr == 0) // Try calling a generic function... if it exists...
FnPtr = (ExFunc)dlsym(RTLD_DEFAULT, ("lle_X_"+M->getName()).c_str());
if (FnPtr != 0)
Functions.insert(make_pair(M, FnPtr)); // Cache for later
return FnPtr;
}
GenericValue Interpreter::callExternalMethod(Method *M,
const vector<GenericValue> &ArgVals) {
TheInterpreter = this;
// Do a lookup to see if the method is in our cache... this should just be a
// defered annotation!
map<const Method *, ExFunc>::iterator FI = Functions.find(M);
ExFunc Fn = (FI == Functions.end()) ? lookupMethod(M) : FI->second;
if (Fn == 0) {
cout << "Tried to execute an unknown external method: "
<< M->getType()->getDescription() << " " << M->getName() << endl;
return GenericValue();
}
// TODO: FIXME when types are not const!
GenericValue Result = Fn(const_cast<MethodType*>(M->getMethodType()),ArgVals);
return Result;
}
//===----------------------------------------------------------------------===//
// Methods "exported" to the running application...
//
extern "C" { // Don't add C++ manglings to llvm mangling :)
// Implement void printstr([ubyte {x N}] *)
GenericValue lle_VP_printstr(MethodType *M, const vector<GenericValue> &ArgVal){
assert(ArgVal.size() == 1 && "printstr only takes one argument!");
cout << (char*)ArgVal[0].PointerVal;
return GenericValue();
}
// Implement 'void print(X)' for every type...
GenericValue lle_X_print(MethodType *M, const vector<GenericValue> &ArgVals) {
assert(ArgVals.size() == 1 && "generic print only takes one argument!");
Interpreter::print(M->getParamTypes()[0], ArgVals[0]);
return GenericValue();
}
// Implement 'void printVal(X)' for every type...
GenericValue lle_X_printVal(MethodType *M, const vector<GenericValue> &ArgVal) {
assert(ArgVal.size() == 1 && "generic print only takes one argument!");
// Specialize print([ubyte {x N} ] *) and print(sbyte *)
if (PointerType *PTy = dyn_cast<PointerType>(M->getParamTypes()[0].get()))
if (PTy->getValueType() == Type::SByteTy ||
isa<ArrayType>(PTy->getValueType())) {
return lle_VP_printstr(M, ArgVal);
}
Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);
return GenericValue();
}
// Implement 'void printString(X)'
// Argument must be [ubyte {x N} ] * or sbyte *
GenericValue lle_X_printString(MethodType *M, const vector<GenericValue> &ArgVal) {
assert(ArgVal.size() == 1 && "generic print only takes one argument!");
return lle_VP_printstr(M, ArgVal);
}
// Implement 'void print<TYPE>(X)' for each primitive type or pointer type
#define PRINT_TYPE_FUNC(TYPENAME,TYPEID) \
GenericValue lle_X_print##TYPENAME(MethodType *M,\
const vector<GenericValue> &ArgVal) {\
assert(ArgVal.size() == 1 && "generic print only takes one argument!");\
assert(M->getParamTypes()[0].get()->getPrimitiveID() == Type::##TYPEID);\
Interpreter::printValue(M->getParamTypes()[0], ArgVal[0]);\
return GenericValue();\
}
PRINT_TYPE_FUNC(SByte, SByteTyID)
PRINT_TYPE_FUNC(UByte, UByteTyID)
PRINT_TYPE_FUNC(Short, ShortTyID)
PRINT_TYPE_FUNC(UShort, UShortTyID)
PRINT_TYPE_FUNC(Int, IntTyID)
PRINT_TYPE_FUNC(UInt, UIntTyID)
PRINT_TYPE_FUNC(Long, LongTyID)
PRINT_TYPE_FUNC(ULong, ULongTyID)
PRINT_TYPE_FUNC(Float, FloatTyID)
PRINT_TYPE_FUNC(Double, DoubleTyID)
PRINT_TYPE_FUNC(Pointer, PointerTyID)
// void "putchar"(sbyte)
GenericValue lle_Vb_putchar(MethodType *M, const vector<GenericValue> &Args) {
cout << Args[0].SByteVal;
return GenericValue();
}
// int "putchar"(int)
GenericValue lle_ii_putchar(MethodType *M, const vector<GenericValue> &Args) {
cout << ((char)Args[0].IntVal) << flush;
return Args[0];
}
// void "putchar"(ubyte)
GenericValue lle_VB_putchar(MethodType *M, const vector<GenericValue> &Args) {
cout << Args[0].SByteVal << flush;
return Args[0];
}
// void "__main"()
GenericValue lle_V___main(MethodType *M, const vector<GenericValue> &Args) {
return GenericValue();
}
// void "exit"(int)
GenericValue lle_Vi_exit(MethodType *M, const vector<GenericValue> &Args) {
TheInterpreter->exitCalled(Args[0]);
return GenericValue();
}
// void *malloc(uint)
GenericValue lle_PI_malloc(MethodType *M, const vector<GenericValue> &Args) {
assert(Args.size() == 1 && "Malloc expects one argument!");
GenericValue GV;
GV.PointerVal = (uint64_t)malloc(Args[0].UIntVal);
return GV;
}
// void free(void *)
GenericValue lle_VP_free(MethodType *M, const vector<GenericValue> &Args) {
free((void*)Args[0].PointerVal);
return GenericValue();
}
// double pow(double, double)
GenericValue lle_DDD_pow(MethodType *M, const vector<GenericValue> &Args) {
GenericValue GV;
GV.DoubleVal = pow(Args[0].DoubleVal, Args[1].DoubleVal);
return GV;
}
// int printf(sbyte *, ...) - a very rough implementation to make output useful.
GenericValue lle_iP_printf(MethodType *M, const vector<GenericValue> &Args) {
const char *FmtStr = (const char *)Args[0].PointerVal;
unsigned ArgNo = 1;
// printf should return # chars printed. This is completely incorrect, but
// close enough for now.
GenericValue GV; GV.IntVal = strlen(FmtStr);
while (1) {
switch (*FmtStr) {
case 0: return GV; // Null terminator...
default: // Normal nonspecial character
cout << *FmtStr++;
break;
case '\\': { // Handle escape codes
char Buffer[3];
Buffer[0] = *FmtStr++;
Buffer[1] = *FmtStr++;
Buffer[2] = 0;
cout << Buffer;
break;
}
case '%': { // Handle format specifiers
bool isLong = false;
++FmtStr;
if (*FmtStr == 'l') {
isLong = true;
FmtStr++;
}
switch (*FmtStr) {
case '%': cout << *FmtStr; break; // %%
case 'd': // %d %i
case 'i': cout << Args[ArgNo++].IntVal; break;
case 'u': cout << Args[ArgNo++].UIntVal; break; // %u
case 'o': cout << oct << Args[ArgNo++].UIntVal << dec; break; // %o
case 'x':
case 'X': cout << hex << Args[ArgNo++].UIntVal << dec; break; // %x %X
case 'e': case 'E': case 'g': case 'G': // %[eEgG]
cout /*<< std::scientific*/ << Args[ArgNo++].DoubleVal
/*<< std::fixed*/; break;
case 'f': cout << Args[ArgNo++].DoubleVal; break; // %f
case 'c': cout << Args[ArgNo++].UByteVal; break; // %c
case 's': cout << (char*)Args[ArgNo++].PointerVal; break; // %s
default: cout << "<unknown printf code '" << *FmtStr << "'!>";
ArgNo++; break;
}
++FmtStr;
break;
}
}
}
}
} // End extern "C"
void Interpreter::initializeExternalMethods() {
FuncNames["lle_VP_printstr"] = lle_VP_printstr;
FuncNames["lle_X_print"] = lle_X_print;
FuncNames["lle_X_printVal"] = lle_X_printVal;
FuncNames["lle_X_printString"] = lle_X_printString;
FuncNames["lle_X_printUByte"] = lle_X_printUByte;
FuncNames["lle_X_printSByte"] = lle_X_printSByte;
FuncNames["lle_X_printUShort"] = lle_X_printUShort;
FuncNames["lle_X_printShort"] = lle_X_printShort;
FuncNames["lle_X_printInt"] = lle_X_printInt;
FuncNames["lle_X_printUInt"] = lle_X_printUInt;
FuncNames["lle_X_printLong"] = lle_X_printLong;
FuncNames["lle_X_printULong"] = lle_X_printULong;
FuncNames["lle_X_printFloat"] = lle_X_printFloat;
FuncNames["lle_X_printDouble"] = lle_X_printDouble;
FuncNames["lle_X_printPointer"] = lle_X_printPointer;
FuncNames["lle_Vb_putchar"] = lle_Vb_putchar;
FuncNames["lle_ii_putchar"] = lle_ii_putchar;
FuncNames["lle_VB_putchar"] = lle_VB_putchar;
FuncNames["lle_V___main"] = lle_V___main;
FuncNames["lle_Vi_exit"] = lle_Vi_exit;
FuncNames["lle_PI_malloc"] = lle_PI_malloc;
FuncNames["lle_VP_free"] = lle_VP_free;
FuncNames["lle_DDD_pow"] = lle_DDD_pow;
FuncNames["lle_iP_printf"] = lle_iP_printf;
}
<|endoftext|>
|
<commit_before>#include <lcm/lcm-cpp.hpp>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/passthrough.h>
#include <path_util/path_util.h>
#include <laser_utils/laser_util.h>
#include <lcmtypes/pronto/pointcloud2_t.hpp>
#include <lcmtypes/pronto/pointcloud_t.hpp>
#include <pronto_utils/pronto_vis.hpp> // visualize pt clds
#include <pronto_utils/conversions_lcm.hpp>
#include <ConciseArgs>
namespace pcl
{
// Euclidean Velodyne coordinate, including intensity and ring number.
struct PointXYZIR
{
PCL_ADD_POINT4D; // quad-word XYZ
float intensity; ///< laser intensity reading
uint16_t ring; ///< laser ring number
EIGEN_MAKE_ALIGNED_OPERATOR_NEW // ensure proper alignment
} EIGEN_ALIGN16;
};
POINT_CLOUD_REGISTER_POINT_STRUCT(pcl::PointXYZIR,
(float, x, x)
(float, y, y)
(float, z, z)
(float, intensity, intensity)
(uint16_t, ring, ring))
struct CommandLineConfig
{
bool verbose;
};
class App{
public:
App(boost::shared_ptr<lcm::LCM> &lcm_recv_, boost::shared_ptr<lcm::LCM> &lcm_pub_, const CommandLineConfig& cl_cfg_);
~App(){
}
private:
const CommandLineConfig cl_cfg_;
boost::shared_ptr<lcm::LCM> lcm_recv_;
boost::shared_ptr<lcm::LCM> lcm_pub_;
pronto_vis* pc_vis_ ;
BotParam* botparam_;
BotFrames* botframes_;
void viconHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const pronto::pointcloud2_t* msg);
};
App::App(boost::shared_ptr<lcm::LCM> &lcm_recv_, boost::shared_ptr<lcm::LCM> &lcm_pub_, const CommandLineConfig& cl_cfg_) :
cl_cfg_(cl_cfg_), lcm_recv_(lcm_recv_), lcm_pub_(lcm_pub_)
{
lcm_recv_->subscribe("VELODYNE",&App::viconHandler,this);
cout <<"App Constructed\n";
bool reset = 1;
pc_vis_ = new pronto_vis( lcm_pub_->getUnderlyingLCM() );
// obj: id name type reset
// pts: id name type reset objcoll usergb rgb
pc_vis_->obj_cfg_list.push_back( obj_cfg(70000,"Pose - Velodyne",5,reset) );
pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(70001,"Cloud - Velodyne" ,1,reset, 70000,1, {0.0, 0.0, 1.0} ));
botparam_ = bot_param_new_from_server(lcm_recv_->getUnderlyingLCM(), 0);
botframes_= bot_frames_get_global(lcm_recv_->getUnderlyingLCM(), botparam_);
}
int get_trans_with_utime(BotFrames *bot_frames,
const char *from_frame, const char *to_frame, int64_t utime,
Eigen::Isometry3d & mat){
int status;
double matx[16];
status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx);
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
mat(i,j) = matx[i*4+j];
}
}
return status;
}
void App::viconHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const pronto::pointcloud2_t* msg){
// 1. convert to a pcl point cloud:
pcl::PointCloud<pcl::PointXYZIR>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZIR> ());
pcl::fromLCMPointCloud2( *msg, *cloud);
//pcl::io::savePCDFileASCII ("mm.pcd", *cloud);
// 2. republish the velodyne as a collections message (on the velodyne frame
Eigen::Isometry3d velodyne_to_local;
get_trans_with_utime( botframes_ , "VELODYNE", "local" , msg->utime, velodyne_to_local);
Isometry3dTime velodyne_to_local_T = Isometry3dTime(msg->utime, velodyne_to_local);
pc_vis_->pose_to_lcm_from_list(70000, velodyne_to_local_T);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb (new pcl::PointCloud<pcl::PointXYZRGB> ());
pcl::copyPointCloud(*cloud, *cloud_xyzrgb);
pc_vis_->ptcld_to_lcm_from_list(70001, *cloud_xyzrgb, msg->utime, msg->utime);
// 3. Find the horizontal lidar beam - could use the ring value but PCL filter doesnt handle it
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::copyPointCloud(*cloud, *cloud_xyz);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>);
pcl::PassThrough<pcl::PointXYZ> pass;
pass.setInputCloud (cloud_xyz);
pass.setFilterFieldName ("z");
pass.setFilterLimits (-0.01, 0.01);
//pass.setFilterLimitsNegative (true);
pass.filter (*cloud_filtered);
//pcl::io::savePCDFileASCII ("mm_filtered.pcd", *cloud_filtered);
// 4. republish beam as new message
pronto::pointcloud_t out;
out.utime = msg->utime;
out.seq = msg->seq;
out.frame_id = msg->frame_id;
for (size_t i = 0; i < cloud_filtered->points.size(); i++) {
std::vector<float> point = { cloud_filtered->points[i].x, cloud_filtered->points[i].y, cloud_filtered->points[i].z};
out.points.push_back(point);
}
out.n_points = out.points.size();
out.n_channels = 0;
// lcm_pub_->publish("VELODYNE_HORIZONTAL",&out);
}
int main(int argc, char **argv){
CommandLineConfig cl_cfg;
ConciseArgs parser(argc, argv, "fovision-odometry");
parser.parse();
boost::shared_ptr<lcm::LCM> lcm_recv;
boost::shared_ptr<lcm::LCM> lcm_pub;
lcm_recv = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
lcm_pub = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
App fo= App(lcm_recv, lcm_pub, cl_cfg);
while(0 == lcm_recv->handle());
}
<commit_msg>add to point cloud tool<commit_after>#include <lcm/lcm-cpp.hpp>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/passthrough.h>
#include <path_util/path_util.h>
#include <laser_utils/laser_util.h>
#include <lcmtypes/pronto/pointcloud2_t.hpp>
#include <lcmtypes/pronto/pointcloud_t.hpp>
#include <pronto_utils/pronto_vis.hpp> // visualize pt clds
#include <pronto_utils/conversions_lcm.hpp>
#include <pronto_utils/point_types.hpp> // velodyne data type
#include <ConciseArgs>
struct CommandLineConfig
{
bool reset;
int publish_every;
};
class App{
public:
App(boost::shared_ptr<lcm::LCM> &lcm_recv_, boost::shared_ptr<lcm::LCM> &lcm_pub_, const CommandLineConfig& cl_cfg_);
~App(){
}
private:
const CommandLineConfig cl_cfg_;
int counter_;
boost::shared_ptr<lcm::LCM> lcm_recv_;
boost::shared_ptr<lcm::LCM> lcm_pub_;
pronto_vis* pc_vis_ ;
BotParam* botparam_;
BotFrames* botframes_;
void viconHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const pronto::pointcloud2_t* msg);
};
App::App(boost::shared_ptr<lcm::LCM> &lcm_recv_, boost::shared_ptr<lcm::LCM> &lcm_pub_, const CommandLineConfig& cl_cfg_) :
cl_cfg_(cl_cfg_), lcm_recv_(lcm_recv_), lcm_pub_(lcm_pub_)
{
lcm_recv_->subscribe("VELODYNE",&App::viconHandler,this);
cout <<"App Constructed\n";
pc_vis_ = new pronto_vis( lcm_pub_->getUnderlyingLCM() );
// obj: id name type reset
// pts: id name type reset objcoll usergb rgb
pc_vis_->obj_cfg_list.push_back( obj_cfg(70000,"Pose - Velodyne",5,cl_cfg_.reset) );
pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(70001,"Cloud - Velodyne" ,1,cl_cfg_.reset, 70000,1, {0.0, 0.0, 1.0} ));
botparam_ = bot_param_new_from_server(lcm_recv_->getUnderlyingLCM(), 0);
botframes_= bot_frames_get_global(lcm_recv_->getUnderlyingLCM(), botparam_);
counter_ =0;
}
int get_trans_with_utime(BotFrames *bot_frames,
const char *from_frame, const char *to_frame, int64_t utime,
Eigen::Isometry3d & mat){
int status;
double matx[16];
status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx);
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
mat(i,j) = matx[i*4+j];
}
}
return status;
}
void App::viconHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const pronto::pointcloud2_t* msg){
counter_++;
// 1. convert to a pcl point cloud:
pcl::PointCloud<pcl::PointXYZIR>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZIR> ());
pcl::fromLCMPointCloud2( *msg, *cloud);
//pcl::io::savePCDFileASCII ("mm.pcd", *cloud);
// 2. republish the velodyne as a collections message (on the velodyne frame)
if (counter_ % cl_cfg_.publish_every == 0){
Eigen::Isometry3d velodyne_to_local;
get_trans_with_utime( botframes_ , "VELODYNE", "local" , msg->utime, velodyne_to_local);
Isometry3dTime velodyne_to_local_T = Isometry3dTime(msg->utime, velodyne_to_local);
pc_vis_->pose_to_lcm_from_list(70000, velodyne_to_local_T);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_xyzrgb (new pcl::PointCloud<pcl::PointXYZRGB> ());
pcl::copyPointCloud(*cloud, *cloud_xyzrgb);
pc_vis_->ptcld_to_lcm_from_list(70001, *cloud_xyzrgb, msg->utime, msg->utime);
}
// 3. Find the horizontal lidar beam - could use the ring value but PCL filter doesnt handle it
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::copyPointCloud(*cloud, *cloud_xyz);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>);
pcl::PassThrough<pcl::PointXYZ> pass;
pass.setInputCloud (cloud_xyz);
pass.setFilterFieldName ("z");
pass.setFilterLimits (-0.01, 0.01);
//pass.setFilterLimitsNegative (true);
pass.filter (*cloud_filtered);
//pcl::io::savePCDFileASCII ("mm_filtered.pcd", *cloud_filtered);
// 4. republish beam as new message
pronto::pointcloud_t out;
out.utime = msg->utime;
out.seq = msg->seq;
out.frame_id = msg->frame_id;
for (size_t i = 0; i < cloud_filtered->points.size(); i++) {
std::vector<float> point = { cloud_filtered->points[i].x, cloud_filtered->points[i].y, cloud_filtered->points[i].z};
out.points.push_back(point);
}
out.n_points = out.points.size();
out.n_channels = 0;
// lcm_pub_->publish("VELODYNE_HORIZONTAL",&out);
}
int main(int argc, char **argv){
CommandLineConfig cl_cfg;
cl_cfg.publish_every = 1;
cl_cfg.reset = true;
ConciseArgs parser(argc, argv, "fovision-odometry");
parser.add(cl_cfg.publish_every, "p", "publish_every","Publish every X scans to collections");
parser.add(cl_cfg.reset, "r", "reset","Reset the collections");
parser.parse();
boost::shared_ptr<lcm::LCM> lcm_recv;
boost::shared_ptr<lcm::LCM> lcm_pub;
lcm_recv = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
lcm_pub = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
App fo= App(lcm_recv, lcm_pub, cl_cfg);
while(0 == lcm_recv->handle());
}
<|endoftext|>
|
<commit_before>#include "musicplaylistfoundwidget.h"
#include "musicsourcedownloadthread.h"
#include "musicdownloadquerywyplaylistthread.h"
#include "musicplaylistfoundinfowidget.h"
#include "musicdownloadqueryfactory.h"
#include "musictinyuiobject.h"
#include "musicplaylistfoundcategorywidget.h"
#include <QPushButton>
#include <QGridLayout>
#include <QScrollArea>
#include <QStackedWidget>
#define MIN_LABEL_SIZE 150
#define MAX_LABEL_SIZE 200
MusicPlaylistFoundItemWidget::MusicPlaylistFoundItemWidget(QWidget *parent)
: QLabel(parent)
{
setFixedSize(MIN_LABEL_SIZE, MAX_LABEL_SIZE);
m_topListenButton = new QPushButton(this);
m_topListenButton->setGeometry(0, 0, MIN_LABEL_SIZE, 20);
m_topListenButton->setIcon(QIcon(":/tiny/btn_listen_hover"));
m_topListenButton->setText(" - ");
m_topListenButton->setStyleSheet(MusicUIObject::MBackgroundStyle04 + MusicUIObject::MColorStyle01);
m_playButton = new QPushButton(this);
m_playButton->setGeometry(110, 110, 30, 30);
m_playButton->setCursor(Qt::PointingHandCursor);
m_playButton->setStyleSheet(MusicUIObject::MKGTinyBtnPlaylist);
connect(m_playButton, SIGNAL(clicked()), SLOT(currentPlayListClicked()));
m_iconLabel = new QLabel(this);
m_iconLabel->setGeometry(0, 0, MIN_LABEL_SIZE, MIN_LABEL_SIZE);
m_nameLabel = new QLabel(this);
m_nameLabel->setGeometry(0, 150, MIN_LABEL_SIZE, 25);
m_nameLabel->setText(" - ");
m_creatorLabel = new QLabel(this);
m_creatorLabel->setGeometry(0, 175, MIN_LABEL_SIZE, 25);
m_creatorLabel->setText("by anonymous");
}
MusicPlaylistFoundItemWidget::~MusicPlaylistFoundItemWidget()
{
delete m_topListenButton;
delete m_playButton;
delete m_iconLabel;
delete m_nameLabel;
delete m_creatorLabel;
}
QString MusicPlaylistFoundItemWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicPlaylistFoundItemWidget::setMusicPlaylistItem(const MusicPlaylistItem &item)
{
m_itemData = item;
m_nameLabel->setToolTip(item.m_name);
m_nameLabel->setText(MusicUtils::Widget::elidedText(m_nameLabel->font(), m_nameLabel->toolTip(),
Qt::ElideRight, MIN_LABEL_SIZE));
m_creatorLabel->setToolTip("by " + item.m_nickname);
m_creatorLabel->setText(MusicUtils::Widget::elidedText(m_creatorLabel->font(), m_creatorLabel->toolTip(),
Qt::ElideRight, MIN_LABEL_SIZE));
bool ok = false;
int count = item.m_playCount.toInt(&ok);
if(ok)
{
if(count >= 10000)
{
m_topListenButton->setText(tr("%1Thous").arg(count/10000));
}
else
{
m_topListenButton->setText(QString::number(count));
}
}
else
{
m_topListenButton->setText(item.m_playCount);
}
MusicSourceDownloadThread *download = new MusicSourceDownloadThread(this);
connect(download, SIGNAL(downLoadByteDataChanged(QByteArray)), SLOT(downLoadFinished(QByteArray)));
download->startToDownload(item.m_coverUrl);
}
void MusicPlaylistFoundItemWidget::downLoadFinished(const QByteArray &data)
{
QPixmap pix;
pix.loadFromData(data);
m_iconLabel->setPixmap(pix.scaled(m_iconLabel->size()));
m_topListenButton->raise();
m_playButton->raise();
}
void MusicPlaylistFoundItemWidget::currentPlayListClicked()
{
emit currentPlayListClicked(m_itemData);
}
MusicPlaylistFoundWidget::MusicPlaylistFoundWidget(QWidget *parent)
: MusicFoundAbstractWidget(parent)
{
m_container = new QStackedWidget(this);
layout()->removeWidget(m_mainWindow);
layout()->addWidget(m_container);
m_container->addWidget(m_mainWindow);
m_firstInit = false;
m_infoWidget = nullptr;
m_gridLayout = nullptr;
m_categoryButton = nullptr;
m_downloadThread = M_DOWNLOAD_QUERY_PTR->getPlaylistThread(this);
connect(m_downloadThread, SIGNAL(createPlaylistItems(MusicPlaylistItem)),
SLOT(queryAllFinished(MusicPlaylistItem)));
}
MusicPlaylistFoundWidget::~MusicPlaylistFoundWidget()
{
delete m_infoWidget;
delete m_gridLayout;
// delete m_container;
delete m_categoryButton;
delete m_downloadThread;
}
QString MusicPlaylistFoundWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicPlaylistFoundWidget::setSongName(const QString &name)
{
MusicFoundAbstractWidget::setSongName(name);
m_downloadThread->startSearchSong(MusicDownLoadQueryThreadAbstract::MovieQuery, QString());
}
void MusicPlaylistFoundWidget::resizeWindow()
{
if(!m_resizeWidget.isEmpty())
{
if(m_gridLayout)
{
for(int i=0; i<m_resizeWidget.count(); ++i)
{
m_gridLayout->removeWidget(m_resizeWidget[i]);
}
int lineNumber = width()/MAX_LABEL_SIZE;
for(int i=0; i<m_resizeWidget.count(); ++i)
{
m_gridLayout->addWidget(m_resizeWidget[i], i/lineNumber, i%lineNumber, Qt::AlignCenter);
}
}
}
}
void MusicPlaylistFoundWidget::queryAllFinished(const MusicPlaylistItem &item)
{
if(!m_firstInit)
{
delete m_statusLabel;
m_statusLabel = nullptr;
m_container->removeWidget(m_mainWindow);
QScrollArea *scrollArea = new QScrollArea(this);
scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01);
scrollArea->setWidgetResizable(true);
scrollArea->setFrameShape(QFrame::NoFrame);
scrollArea->setAlignment(Qt::AlignLeft);
scrollArea->setWidget(m_mainWindow);
m_container->addWidget(scrollArea);
m_firstInit = true;
m_categoryButton = new MusicPlaylistFoundCategoryWidget(m_mainWindow);
m_categoryButton->setCategory(m_downloadThread->getQueryServer(), this);
m_mainWindow->layout()->addWidget(m_categoryButton);
QFrame *line = new QFrame(m_mainWindow);
line->setFrameShape(QFrame::HLine);
line->setStyleSheet(MusicUIObject::MColorStyle06);
m_mainWindow->layout()->addWidget(line);
QWidget *containWidget = new QWidget(m_mainWindow);
m_gridLayout = new QGridLayout(containWidget);
m_gridLayout->setVerticalSpacing(35);
containWidget->setLayout(m_gridLayout);
m_mainWindow->layout()->addWidget(containWidget);
}
MusicPlaylistFoundItemWidget *label = new MusicPlaylistFoundItemWidget(this);
connect(label, SIGNAL(currentPlayListClicked(MusicPlaylistItem)), SLOT(currentPlayListClicked(MusicPlaylistItem)));
label->setMusicPlaylistItem(item);
int lineNumber = width()/MAX_LABEL_SIZE;
m_gridLayout->addWidget(label, m_resizeWidget.count()/lineNumber,
m_resizeWidget.count()%lineNumber, Qt::AlignCenter);
m_resizeWidget << label;
}
void MusicPlaylistFoundWidget::currentPlayListClicked(const MusicPlaylistItem &item)
{
delete m_infoWidget;
m_infoWidget = new MusicPlaylistFoundInfoWidget(this);
m_infoWidget->setQueryInput(M_DOWNLOAD_QUERY_PTR->getPlaylistThread(this));
m_infoWidget->setMusicPlaylistItem(item, this);
m_container->addWidget(m_infoWidget);
m_container->setCurrentIndex(1);
}
void MusicPlaylistFoundWidget::backToPlayListMenu()
{
m_container->setCurrentIndex(0);
}
void MusicPlaylistFoundWidget::categoryChanged(const PlaylistCategoryItem &category)
{
if(m_categoryButton)
{
m_categoryButton->setText(category.m_name);
m_categoryButton->closeMenu();
while(!m_resizeWidget.isEmpty())
{
QWidget *w = m_resizeWidget.takeLast();
m_gridLayout->removeWidget(w);
delete w;
}
m_downloadThread->startSearchSong(MusicDownLoadQueryThreadAbstract::MovieQuery, category.m_id);
}
}
void MusicPlaylistFoundWidget::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
resizeWindow();
}
<commit_msg>Add playlist category found widget[509485]<commit_after>#include "musicplaylistfoundwidget.h"
#include "musicsourcedownloadthread.h"
#include "musicdownloadquerywyplaylistthread.h"
#include "musicplaylistfoundinfowidget.h"
#include "musicdownloadqueryfactory.h"
#include "musictinyuiobject.h"
#include "musicplaylistfoundcategorywidget.h"
#include <QPushButton>
#include <QGridLayout>
#include <QScrollArea>
#include <QStackedWidget>
#define MIN_LABEL_SIZE 150
#define MAX_LABEL_SIZE 200
MusicPlaylistFoundItemWidget::MusicPlaylistFoundItemWidget(QWidget *parent)
: QLabel(parent)
{
setFixedSize(MIN_LABEL_SIZE, MAX_LABEL_SIZE);
m_topListenButton = new QPushButton(this);
m_topListenButton->setGeometry(0, 0, MIN_LABEL_SIZE, 20);
m_topListenButton->setIcon(QIcon(":/tiny/btn_listen_hover"));
m_topListenButton->setText(" - ");
m_topListenButton->setStyleSheet(MusicUIObject::MBackgroundStyle04 + MusicUIObject::MColorStyle01);
m_playButton = new QPushButton(this);
m_playButton->setGeometry(110, 110, 30, 30);
m_playButton->setCursor(Qt::PointingHandCursor);
m_playButton->setStyleSheet(MusicUIObject::MKGTinyBtnPlaylist);
connect(m_playButton, SIGNAL(clicked()), SLOT(currentPlayListClicked()));
m_iconLabel = new QLabel(this);
m_iconLabel->setGeometry(0, 0, MIN_LABEL_SIZE, MIN_LABEL_SIZE);
m_nameLabel = new QLabel(this);
m_nameLabel->setGeometry(0, 150, MIN_LABEL_SIZE, 25);
m_nameLabel->setText(" - ");
m_creatorLabel = new QLabel(this);
m_creatorLabel->setGeometry(0, 175, MIN_LABEL_SIZE, 25);
m_creatorLabel->setText("by anonymous");
}
MusicPlaylistFoundItemWidget::~MusicPlaylistFoundItemWidget()
{
delete m_topListenButton;
delete m_playButton;
delete m_iconLabel;
delete m_nameLabel;
delete m_creatorLabel;
}
QString MusicPlaylistFoundItemWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicPlaylistFoundItemWidget::setMusicPlaylistItem(const MusicPlaylistItem &item)
{
m_itemData = item;
m_nameLabel->setToolTip(item.m_name);
m_nameLabel->setText(MusicUtils::Widget::elidedText(m_nameLabel->font(), m_nameLabel->toolTip(),
Qt::ElideRight, MIN_LABEL_SIZE));
m_creatorLabel->setToolTip("by " + item.m_nickname);
m_creatorLabel->setText(MusicUtils::Widget::elidedText(m_creatorLabel->font(), m_creatorLabel->toolTip(),
Qt::ElideRight, MIN_LABEL_SIZE));
bool ok = false;
int count = item.m_playCount.toInt(&ok);
if(ok)
{
if(count >= 10000)
{
m_topListenButton->setText(tr("%1Thous").arg(count/10000));
}
else
{
m_topListenButton->setText(QString::number(count));
}
}
else
{
m_topListenButton->setText(item.m_playCount);
}
MusicSourceDownloadThread *download = new MusicSourceDownloadThread(this);
connect(download, SIGNAL(downLoadByteDataChanged(QByteArray)), SLOT(downLoadFinished(QByteArray)));
download->startToDownload(item.m_coverUrl);
}
void MusicPlaylistFoundItemWidget::downLoadFinished(const QByteArray &data)
{
QPixmap pix;
pix.loadFromData(data);
m_iconLabel->setPixmap(pix.scaled(m_iconLabel->size()));
m_topListenButton->raise();
m_playButton->raise();
}
void MusicPlaylistFoundItemWidget::currentPlayListClicked()
{
emit currentPlayListClicked(m_itemData);
}
MusicPlaylistFoundWidget::MusicPlaylistFoundWidget(QWidget *parent)
: MusicFoundAbstractWidget(parent)
{
m_container = new QStackedWidget(this);
layout()->removeWidget(m_mainWindow);
layout()->addWidget(m_container);
m_container->addWidget(m_mainWindow);
m_firstInit = false;
m_infoWidget = nullptr;
m_gridLayout = nullptr;
m_categoryButton = nullptr;
m_downloadThread = M_DOWNLOAD_QUERY_PTR->getPlaylistThread(this);
connect(m_downloadThread, SIGNAL(createPlaylistItems(MusicPlaylistItem)),
SLOT(queryAllFinished(MusicPlaylistItem)));
}
MusicPlaylistFoundWidget::~MusicPlaylistFoundWidget()
{
delete m_infoWidget;
delete m_gridLayout;
// delete m_container;
delete m_categoryButton;
delete m_downloadThread;
}
QString MusicPlaylistFoundWidget::getClassName()
{
return staticMetaObject.className();
}
void MusicPlaylistFoundWidget::setSongName(const QString &name)
{
MusicFoundAbstractWidget::setSongName(name);
m_downloadThread->startSearchSong(MusicDownLoadQueryThreadAbstract::MovieQuery, QString());
}
void MusicPlaylistFoundWidget::resizeWindow()
{
if(!m_resizeWidget.isEmpty())
{
if(m_gridLayout)
{
for(int i=0; i<m_resizeWidget.count(); ++i)
{
m_gridLayout->removeWidget(m_resizeWidget[i]);
}
int lineNumber = width()/MAX_LABEL_SIZE;
for(int i=0; i<m_resizeWidget.count(); ++i)
{
m_gridLayout->addWidget(m_resizeWidget[i], i/lineNumber, i%lineNumber, Qt::AlignCenter);
}
}
}
}
void MusicPlaylistFoundWidget::queryAllFinished(const MusicPlaylistItem &item)
{
if(!m_firstInit)
{
delete m_statusLabel;
m_statusLabel = nullptr;
m_container->removeWidget(m_mainWindow);
QScrollArea *scrollArea = new QScrollArea(this);
scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01);
scrollArea->setWidgetResizable(true);
scrollArea->setFrameShape(QFrame::NoFrame);
scrollArea->setAlignment(Qt::AlignLeft);
scrollArea->setWidget(m_mainWindow);
m_container->addWidget(scrollArea);
m_firstInit = true;
QHBoxLayout *mainlayout = MStatic_cast(QHBoxLayout*, m_mainWindow->layout());
QWidget *containTopWidget = new QWidget(m_mainWindow);
QHBoxLayout *containTopLayout = new QHBoxLayout(containTopWidget);
containTopLayout->setContentsMargins(30, 0, 30, 0);
m_categoryButton = new MusicPlaylistFoundCategoryWidget(m_mainWindow);
m_categoryButton->setCategory(m_downloadThread->getQueryServer(), this);
containTopLayout->addWidget(m_categoryButton);
containTopLayout->addStretch(1);
foreach(const QString &data, QStringList() << tr("Recommend") << tr("Top") << tr("Hot") << tr("New"))
{
QLabel *l = new QLabel(data, containTopWidget);
l->setStyleSheet(QString("QLabel::hover{%1}").arg(MusicUIObject::MColorStyle08));
QFrame *hline = new QFrame(containTopWidget);
hline->setFrameShape(QFrame::VLine);
hline->setStyleSheet(MusicUIObject::MColorStyle06);
containTopLayout->addWidget(l);
containTopLayout->addWidget(hline);
}
QFrame *line = new QFrame(m_mainWindow);
line->setFrameShape(QFrame::HLine);
line->setStyleSheet(MusicUIObject::MColorStyle06);
QWidget *containWidget = new QWidget(m_mainWindow);
m_gridLayout = new QGridLayout(containWidget);
m_gridLayout->setVerticalSpacing(35);
containWidget->setLayout(m_gridLayout);
mainlayout->addWidget(containTopWidget);
mainlayout->addWidget(line);
mainlayout->addWidget(containWidget);
mainlayout->addStretch(1);
}
MusicPlaylistFoundItemWidget *label = new MusicPlaylistFoundItemWidget(this);
connect(label, SIGNAL(currentPlayListClicked(MusicPlaylistItem)), SLOT(currentPlayListClicked(MusicPlaylistItem)));
label->setMusicPlaylistItem(item);
int lineNumber = width()/MAX_LABEL_SIZE;
m_gridLayout->addWidget(label, m_resizeWidget.count()/lineNumber,
m_resizeWidget.count()%lineNumber, Qt::AlignCenter);
m_resizeWidget << label;
}
void MusicPlaylistFoundWidget::currentPlayListClicked(const MusicPlaylistItem &item)
{
delete m_infoWidget;
m_infoWidget = new MusicPlaylistFoundInfoWidget(this);
m_infoWidget->setQueryInput(M_DOWNLOAD_QUERY_PTR->getPlaylistThread(this));
m_infoWidget->setMusicPlaylistItem(item, this);
m_container->addWidget(m_infoWidget);
m_container->setCurrentIndex(1);
}
void MusicPlaylistFoundWidget::backToPlayListMenu()
{
m_container->setCurrentIndex(0);
}
void MusicPlaylistFoundWidget::categoryChanged(const PlaylistCategoryItem &category)
{
if(m_categoryButton)
{
m_categoryButton->setText(category.m_name);
m_categoryButton->closeMenu();
while(!m_resizeWidget.isEmpty())
{
QWidget *w = m_resizeWidget.takeLast();
m_gridLayout->removeWidget(w);
delete w;
}
m_downloadThread->startSearchSong(MusicDownLoadQueryThreadAbstract::MovieQuery, category.m_id);
}
}
void MusicPlaylistFoundWidget::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
resizeWindow();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: core_resource.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 13:36:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBA_CORE_RESOURCE_HXX_
#define _DBA_CORE_RESOURCE_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
class SimpleResMgr;
//.........................................................................
namespace dbaccess
{
#define DBACORE_RESSTRING(id) ResourceManager::loadString(id)
//==================================================================
//= ResourceManager
//= handling ressources within the DBA-Core library
//==================================================================
class ResourceManager
{
static SimpleResMgr* m_pImpl;
private:
// no instantiation allowed
ResourceManager() { }
~ResourceManager() { }
// we'll instantiate one static member of the following class, which, in it's dtor,
// ensures that m_pImpl will be deleted
class EnsureDelete
{
public:
EnsureDelete() { }
~EnsureDelete();
};
friend class EnsureDelete;
protected:
static void ensureImplExists();
public:
/** loads the string with the specified resource id from the FormLayer resource file
*/
static ::rtl::OUString loadString(sal_uInt16 _nResId);
};
//.........................................................................
}
//.........................................................................
#endif // _DBA_CORE_RESOURCE_HXX_
<commit_msg>INTEGRATION: CWS qiq (1.3.124); FILE MERGED 2006/06/09 11:55:43 fs 1.3.124.1: #i51143# +loadString with placeholder replacement<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: core_resource.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-07-10 15:13:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBA_CORE_RESOURCE_HXX_
#define _DBA_CORE_RESOURCE_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
class SimpleResMgr;
//.........................................................................
namespace dbaccess
{
#define DBA_RES( id ) ResourceManager::loadString( id )
#define DBA_RES_PARAM( id, ascii, replace ) ResourceManager::loadString( id, ascii, replace )
#define DBACORE_RESSTRING( id ) DBA_RES( id )
// (compatibility)
//==================================================================
//= ResourceManager
//= handling ressources within the DBA-Core library
//==================================================================
class ResourceManager
{
static SimpleResMgr* m_pImpl;
private:
// no instantiation allowed
ResourceManager() { }
~ResourceManager() { }
// we'll instantiate one static member of the following class, which, in it's dtor,
// ensures that m_pImpl will be deleted
class EnsureDelete
{
public:
EnsureDelete() { }
~EnsureDelete();
};
friend class EnsureDelete;
protected:
static void ensureImplExists();
public:
/** loads the string with the specified resource id
*/
static ::rtl::OUString loadString(sal_uInt16 _nResId);
/** loads a string from the resource file, substituting a placeholder with a given string
@param _nResId
the resource ID of the string to loAD
@param _pPlaceholderAscii
the ASCII representation of the placeholder string
@param _rReplace
the string which should substutite the placeholder
*/
static ::rtl::OUString loadString(
sal_uInt16 _nResId,
const sal_Char* _pPlaceholderAscii,
const ::rtl::OUString& _rReplace
);
};
//.........................................................................
}
//.........................................................................
#endif // _DBA_CORE_RESOURCE_HXX_
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SqlNameEdit.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2006-09-17 07:00:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_SQLNAMEEDIT_HXX
#include "SqlNameEdit.hxx"
#endif
namespace dbaui
{
//------------------------------------------------------------------
sal_Bool isCharOk(sal_Unicode _cChar,sal_Bool _bFirstChar,sal_Bool _bUpperCase,const ::rtl::OUString& _sAllowedChars)
{
return (_cChar >= 'A' && _cChar <= 'Z' ||
_cChar == '_' ||
_sAllowedChars.indexOf(_cChar) != -1 ||
(!_bFirstChar && (_cChar >= '0' && _cChar <= '9')) ||
(!_bUpperCase && (_cChar >= 'a' && _cChar <= 'z')));
}
//------------------------------------------------------------------
sal_Bool OSQLNameChecker::checkString( const ::rtl::OUString& _sOldValue,
const ::rtl::OUString& _sToCheck,
::rtl::OUString& _rsCorrected)
{
sal_Bool bCorrected = sal_False;
if ( m_bCheck )
{
XubString sSavedValue = _sOldValue;
XubString sText = _sToCheck;
xub_StrLen nMatch = 0;
for ( xub_StrLen i=nMatch;i < sText.Len(); ++i )
{
if ( !isCharOk( sText.GetBuffer()[i], i == 0, m_bOnlyUpperCase, m_sAllowedChars ) )
{
_rsCorrected += sText.Copy( nMatch, i - nMatch );
bCorrected = sal_True;
nMatch = i + 1;
}
}
_rsCorrected += sText.Copy( nMatch, sText.Len() - nMatch );
}
return bCorrected;
}
//------------------------------------------------------------------
void OSQLNameEdit::Modify()
{
::rtl::OUString sCorrected;
if ( checkString( GetSavedValue(),GetText(),sCorrected ) )
{
Selection aSel = GetSelection();
aSel.setMax( aSel.getMin() );
SetText( sCorrected, aSel );
SaveValue();
}
Edit::Modify();
}
//------------------------------------------------------------------
void OSQLNameComboBox::Modify()
{
::rtl::OUString sCorrected;
if ( checkString( GetSavedValue(),GetText(),sCorrected ) )
{
Selection aSel = GetSelection();
aSel.setMax( aSel.getMin() );
SetText( sCorrected );
SaveValue();
}
ComboBox::Modify();
}
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.9.258); FILE MERGED 2008/03/31 13:27:10 rt 1.9.258.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SqlNameEdit.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_SQLNAMEEDIT_HXX
#include "SqlNameEdit.hxx"
#endif
namespace dbaui
{
//------------------------------------------------------------------
sal_Bool isCharOk(sal_Unicode _cChar,sal_Bool _bFirstChar,sal_Bool _bUpperCase,const ::rtl::OUString& _sAllowedChars)
{
return (_cChar >= 'A' && _cChar <= 'Z' ||
_cChar == '_' ||
_sAllowedChars.indexOf(_cChar) != -1 ||
(!_bFirstChar && (_cChar >= '0' && _cChar <= '9')) ||
(!_bUpperCase && (_cChar >= 'a' && _cChar <= 'z')));
}
//------------------------------------------------------------------
sal_Bool OSQLNameChecker::checkString( const ::rtl::OUString& _sOldValue,
const ::rtl::OUString& _sToCheck,
::rtl::OUString& _rsCorrected)
{
sal_Bool bCorrected = sal_False;
if ( m_bCheck )
{
XubString sSavedValue = _sOldValue;
XubString sText = _sToCheck;
xub_StrLen nMatch = 0;
for ( xub_StrLen i=nMatch;i < sText.Len(); ++i )
{
if ( !isCharOk( sText.GetBuffer()[i], i == 0, m_bOnlyUpperCase, m_sAllowedChars ) )
{
_rsCorrected += sText.Copy( nMatch, i - nMatch );
bCorrected = sal_True;
nMatch = i + 1;
}
}
_rsCorrected += sText.Copy( nMatch, sText.Len() - nMatch );
}
return bCorrected;
}
//------------------------------------------------------------------
void OSQLNameEdit::Modify()
{
::rtl::OUString sCorrected;
if ( checkString( GetSavedValue(),GetText(),sCorrected ) )
{
Selection aSel = GetSelection();
aSel.setMax( aSel.getMin() );
SetText( sCorrected, aSel );
SaveValue();
}
Edit::Modify();
}
//------------------------------------------------------------------
void OSQLNameComboBox::Modify()
{
::rtl::OUString sCorrected;
if ( checkString( GetSavedValue(),GetText(),sCorrected ) )
{
Selection aSel = GetSelection();
aSel.setMax( aSel.getMin() );
SetText( sCorrected );
SaveValue();
}
ComboBox::Modify();
}
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 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/debugger/devtools_http_protocol_handler.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
#include "net/base/listen_socket.h"
#include "net/server/http_server_request_info.h"
#include "net/url_request/url_request_context.h"
const int kBufferSize = 16 * 1024;
namespace {
// An internal implementation of DevToolsClientHost that delegates
// messages sent for DevToolsClient to a DebuggerShell instance.
class DevToolsClientHostImpl : public DevToolsClientHost {
public:
explicit DevToolsClientHostImpl(HttpListenSocket* socket)
: socket_(socket) {}
~DevToolsClientHostImpl() {}
// DevToolsClientHost interface
virtual void InspectedTabClosing() {
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(socket_,
&HttpListenSocket::Close));
}
virtual void SendMessageToClient(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void NotifyCloseListener() {
DevToolsClientHost::NotifyCloseListener();
}
private:
// Message handling routines
void OnRpcMessage(const DevToolsMessageData& data) {
std::string message;
message += "devtools$$dispatch(\"" + data.class_name + "\", \"" +
data.method_name + "\"";
for (std::vector<std::string>::const_iterator it = data.arguments.begin();
it != data.arguments.end(); ++it) {
std::string param = *it;
if (!param.empty())
message += ", " + param;
}
message += ")";
socket_->SendOverWebSocket(message);
}
HttpListenSocket* socket_;
};
}
DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {
// Stop() must be called prior to this being called
DCHECK(server_.get() == NULL);
}
void DevToolsHttpProtocolHandler::Start() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));
}
void DevToolsHttpProtocolHandler::Stop() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));
}
void DevToolsHttpProtocolHandler::OnHttpRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
if (info.path == "" || info.path == "/") {
// Pages discovery request.
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(this,
&DevToolsHttpProtocolHandler::OnHttpRequestUI,
socket,
info));
return;
}
size_t pos = info.path.find("/devtools/");
if (pos != 0) {
socket->Send404();
return;
}
// Proxy static files from chrome://devtools/*.
URLRequest* request = new URLRequest(GURL("chrome:/" + info.path), this);
Bind(request, socket);
request->set_context(
Profile::GetDefaultRequestContext()->GetURLRequestContext());
request->Start();
}
void DevToolsHttpProtocolHandler::OnWebSocketRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketRequestUI,
socket,
request));
}
void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,
const std::string& data) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketMessageUI,
socket,
data));
}
void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it != socket_to_requests_io_.end()) {
// Dispose delegating socket.
for (std::set<URLRequest*>::iterator it2 = it->second.begin();
it2 != it->second.end(); ++it2) {
URLRequest* request = *it2;
request->Cancel();
request_to_socket_io_.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
socket_to_requests_io_.erase(socket);
}
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnCloseUI,
socket));
}
void DevToolsHttpProtocolHandler::OnHttpRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
std::string response = "<html><body>";
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
TabContents* tab_contents = model->GetTabContentsAt(i);
NavigationController& controller = tab_contents->controller();
NavigationEntry* entry = controller.GetActiveEntry();
if (entry == NULL)
continue;
if (!entry->url().is_valid())
continue;
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(tab_contents->render_view_host());
if (!client_host) {
response += StringPrintf(
"<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>",
controller.session_id().id(),
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
} else {
response += StringPrintf(
"%s (%s)<br>",
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
}
}
}
response += "</body></html>";
Send200(socket, response, "text/html");
}
void DevToolsHttpProtocolHandler::OnWebSocketRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
std::string prefix = "/devtools/page/";
size_t pos = request.path.find(prefix);
if (pos != 0) {
Send404(socket);
return;
}
std::string page_id = request.path.substr(prefix.length());
int id = 0;
if (!StringToInt(page_id, &id)) {
Send500(socket, "Invalid page id: " + page_id);
return;
}
TabContents* tab_contents = GetTabContents(id);
if (tab_contents == NULL) {
Send500(socket, "No such page id: " + page_id);
return;
}
DevToolsManager* manager = DevToolsManager::GetInstance();
if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {
Send500(socket, "Page with given id is being inspected: " + page_id);
return;
}
DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);
socket_to_client_host_ui_[socket] = client_host;
manager->RegisterDevToolsClientHostFor(
tab_contents->render_view_host(),
client_host);
AcceptWebSocket(socket, request);
}
void DevToolsHttpProtocolHandler::OnWebSocketMessageUI(
HttpListenSocket* socket,
const std::string& d) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
std::string data = d;
// TODO(pfeldman): Replace with proper parsing / dispatching.
DevToolsMessageData message_data;
message_data.class_name = "ToolsAgent";
message_data.method_name = "dispatchOnInspectorController";
size_t pos = data.find(" ");
message_data.arguments.push_back(data.substr(0, pos));
data = data.substr(pos + 1);
message_data.arguments.push_back(data);
DevToolsManager* manager = DevToolsManager::GetInstance();
manager->ForwardToDevToolsAgent(it->second,
DevToolsAgentMsg_RpcMessage(DevToolsMessageData(message_data)));
}
void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
DevToolsClientHostImpl* client_host =
static_cast<DevToolsClientHostImpl*>(it->second);
client_host->NotifyCloseListener();
delete client_host;
socket_to_client_host_ui_.erase(socket);
}
void DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
int expected_size = static_cast<int>(request->GetExpectedContentSize());
std::string content_type;
request->GetMimeType(&content_type);
if (request->status().is_success()) {
socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n"
"Content-Type:%s\r\n"
"Content-Length:%d\r\n"
"\r\n",
content_type.c_str(),
expected_size));
} else {
socket->Send404();
}
int bytes_read = 0;
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
if (request->status().is_success())
request->Read(buffer, kBufferSize, &bytes_read);
OnReadCompleted(request, bytes_read);
}
void DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request,
int bytes_read) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
do {
if (!request->status().is_success() || bytes_read <= 0)
break;
socket->Send(buffer->data(), bytes_read);
} while (request->Read(buffer, kBufferSize, &bytes_read));
// See comments re: HEAD requests in OnResponseStarted().
if (!request->status().is_io_pending())
RequestCompleted(request);
}
DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)
: port_(port),
server_(NULL) {
}
void DevToolsHttpProtocolHandler::Init() {
server_ = HttpListenSocket::Listen("127.0.0.1", port_, this);
}
// Run on I/O thread
void DevToolsHttpProtocolHandler::Teardown() {
server_ = NULL;
}
void DevToolsHttpProtocolHandler::Bind(URLRequest* request,
HttpListenSocket* socket) {
request_to_socket_io_[request] = socket;
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it == socket_to_requests_io_.end()) {
std::pair<HttpListenSocket*, std::set<URLRequest*> > value(
socket,
std::set<URLRequest*>());
it = socket_to_requests_io_.insert(value).first;
}
it->second.insert(request);
request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);
}
void DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
request_to_socket_io_.erase(request);
SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);
it2->second.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,
const std::string& data,
const std::string& mime_type) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send200,
data,
mime_type));
}
void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send404));
}
void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,
const std::string& message) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send500,
message));
}
void DevToolsHttpProtocolHandler::AcceptWebSocket(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::AcceptWebSocket,
request));
}
TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
NavigationController& controller =
model->GetTabContentsAt(i)->controller();
if (controller.session_id().id() == session_id)
return controller.tab_contents();
}
}
return NULL;
}
<commit_msg>DevTools: restore remote rebugging after upstream breakage.<commit_after>// Copyright (c) 2010 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/debugger/devtools_http_protocol_handler.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop_proxy.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
#include "net/base/listen_socket.h"
#include "net/server/http_server_request_info.h"
#include "net/url_request/url_request_context.h"
const int kBufferSize = 16 * 1024;
namespace {
// An internal implementation of DevToolsClientHost that delegates
// messages sent for DevToolsClient to a DebuggerShell instance.
class DevToolsClientHostImpl : public DevToolsClientHost {
public:
explicit DevToolsClientHostImpl(HttpListenSocket* socket)
: socket_(socket) {}
~DevToolsClientHostImpl() {}
// DevToolsClientHost interface
virtual void InspectedTabClosing() {
ChromeThread::PostTask(
ChromeThread::IO,
FROM_HERE,
NewRunnableMethod(socket_,
&HttpListenSocket::Close));
}
virtual void SendMessageToClient(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)
IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage);
IPC_MESSAGE_UNHANDLED_ERROR()
IPC_END_MESSAGE_MAP()
}
void NotifyCloseListener() {
DevToolsClientHost::NotifyCloseListener();
}
private:
// Message handling routines
void OnRpcMessage(const DevToolsMessageData& data) {
std::string message;
message += "devtools$$dispatch(\"" + data.class_name + "\", \"" +
data.method_name + "\"";
for (std::vector<std::string>::const_iterator it = data.arguments.begin();
it != data.arguments.end(); ++it) {
std::string param = *it;
if (!param.empty())
message += ", " + param;
}
message += ")";
socket_->SendOverWebSocket(message);
}
HttpListenSocket* socket_;
};
}
DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {
// Stop() must be called prior to this being called
DCHECK(server_.get() == NULL);
}
void DevToolsHttpProtocolHandler::Start() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));
}
void DevToolsHttpProtocolHandler::Stop() {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));
}
void DevToolsHttpProtocolHandler::OnHttpRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
if (info.path == "" || info.path == "/") {
// Pages discovery request.
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(this,
&DevToolsHttpProtocolHandler::OnHttpRequestUI,
socket,
info));
return;
}
size_t pos = info.path.find("/devtools/");
if (pos != 0) {
socket->Send404();
return;
}
// Proxy static files from chrome://devtools/*.
URLRequest* request = new URLRequest(GURL("chrome:/" + info.path), this);
Bind(request, socket);
request->set_context(
Profile::GetDefaultRequestContext()->GetURLRequestContext());
request->Start();
}
void DevToolsHttpProtocolHandler::OnWebSocketRequest(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketRequestUI,
socket,
request));
}
void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,
const std::string& data) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnWebSocketMessageUI,
socket,
data));
}
void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it != socket_to_requests_io_.end()) {
// Dispose delegating socket.
for (std::set<URLRequest*>::iterator it2 = it->second.begin();
it2 != it->second.end(); ++it2) {
URLRequest* request = *it2;
request->Cancel();
request_to_socket_io_.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
socket_to_requests_io_.erase(socket);
}
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(
this,
&DevToolsHttpProtocolHandler::OnCloseUI,
socket));
}
void DevToolsHttpProtocolHandler::OnHttpRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& info) {
std::string response = "<html><body>";
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
TabContents* tab_contents = model->GetTabContentsAt(i);
NavigationController& controller = tab_contents->controller();
NavigationEntry* entry = controller.GetActiveEntry();
if (entry == NULL)
continue;
if (!entry->url().is_valid())
continue;
DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
GetDevToolsClientHostFor(tab_contents->render_view_host());
if (!client_host) {
response += StringPrintf(
"<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>",
controller.session_id().id(),
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
} else {
response += StringPrintf(
"%s (%s)<br>",
UTF16ToUTF8(entry->title()).c_str(),
entry->url().spec().c_str());
}
}
}
response += "</body></html>";
Send200(socket, response, "text/html");
}
void DevToolsHttpProtocolHandler::OnWebSocketRequestUI(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
std::string prefix = "/devtools/page/";
size_t pos = request.path.find(prefix);
if (pos != 0) {
Send404(socket);
return;
}
std::string page_id = request.path.substr(prefix.length());
int id = 0;
if (!StringToInt(page_id, &id)) {
Send500(socket, "Invalid page id: " + page_id);
return;
}
TabContents* tab_contents = GetTabContents(id);
if (tab_contents == NULL) {
Send500(socket, "No such page id: " + page_id);
return;
}
DevToolsManager* manager = DevToolsManager::GetInstance();
if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {
Send500(socket, "Page with given id is being inspected: " + page_id);
return;
}
DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);
socket_to_client_host_ui_[socket] = client_host;
manager->RegisterDevToolsClientHostFor(
tab_contents->render_view_host(),
client_host);
AcceptWebSocket(socket, request);
}
void DevToolsHttpProtocolHandler::OnWebSocketMessageUI(
HttpListenSocket* socket,
const std::string& data) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
// TODO(pfeldman): Replace with proper parsing / dispatching.
DevToolsMessageData message_data;
message_data.class_name = "ToolsAgent";
message_data.method_name = "dispatchOnInspectorController";
message_data.arguments.push_back(data);
DevToolsManager* manager = DevToolsManager::GetInstance();
manager->ForwardToDevToolsAgent(it->second,
DevToolsAgentMsg_RpcMessage(DevToolsMessageData(message_data)));
}
void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {
SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);
if (it == socket_to_client_host_ui_.end())
return;
DevToolsClientHostImpl* client_host =
static_cast<DevToolsClientHostImpl*>(it->second);
client_host->NotifyCloseListener();
delete client_host;
socket_to_client_host_ui_.erase(socket);
}
void DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
int expected_size = static_cast<int>(request->GetExpectedContentSize());
std::string content_type;
request->GetMimeType(&content_type);
if (request->status().is_success()) {
socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n"
"Content-Type:%s\r\n"
"Content-Length:%d\r\n"
"\r\n",
content_type.c_str(),
expected_size));
} else {
socket->Send404();
}
int bytes_read = 0;
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
if (request->status().is_success())
request->Read(buffer, kBufferSize, &bytes_read);
OnReadCompleted(request, bytes_read);
}
void DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request,
int bytes_read) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
net::IOBuffer* buffer = request_to_buffer_io_[request].get();
do {
if (!request->status().is_success() || bytes_read <= 0)
break;
socket->Send(buffer->data(), bytes_read);
} while (request->Read(buffer, kBufferSize, &bytes_read));
// See comments re: HEAD requests in OnResponseStarted().
if (!request->status().is_io_pending())
RequestCompleted(request);
}
DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)
: port_(port),
server_(NULL) {
}
void DevToolsHttpProtocolHandler::Init() {
server_ = HttpListenSocket::Listen("127.0.0.1", port_, this);
}
// Run on I/O thread
void DevToolsHttpProtocolHandler::Teardown() {
server_ = NULL;
}
void DevToolsHttpProtocolHandler::Bind(URLRequest* request,
HttpListenSocket* socket) {
request_to_socket_io_[request] = socket;
SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);
if (it == socket_to_requests_io_.end()) {
std::pair<HttpListenSocket*, std::set<URLRequest*> > value(
socket,
std::set<URLRequest*>());
it = socket_to_requests_io_.insert(value).first;
}
it->second.insert(request);
request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);
}
void DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) {
RequestToSocketMap::iterator it = request_to_socket_io_.find(request);
if (it == request_to_socket_io_.end())
return;
HttpListenSocket* socket = it->second;
request_to_socket_io_.erase(request);
SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);
it2->second.erase(request);
request_to_buffer_io_.erase(request);
delete request;
}
void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,
const std::string& data,
const std::string& mime_type) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send200,
data,
mime_type));
}
void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send404));
}
void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,
const std::string& message) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::Send500,
message));
}
void DevToolsHttpProtocolHandler::AcceptWebSocket(
HttpListenSocket* socket,
const HttpServerRequestInfo& request) {
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(socket,
&HttpListenSocket::AcceptWebSocket,
request));
}
TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {
for (BrowserList::const_iterator it = BrowserList::begin(),
end = BrowserList::end(); it != end; ++it) {
TabStripModel* model = (*it)->tabstrip_model();
for (int i = 0, size = model->count(); i < size; ++i) {
NavigationController& controller =
model->GetTabContentsAt(i)->controller();
if (controller.session_id().id() == session_id)
return controller.tab_contents();
}
}
return NULL;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_webkit_preferences.h"
#include "chrome/common/extensions/extension.h"
#include "webkit/glue/webpreferences.h"
namespace extension_webkit_preferences {
void SetPreferences(const Extension* extension,
content::ViewType render_view_type,
WebPreferences* webkit_prefs) {
if (extension && !extension->is_hosted_app()) {
// Extensions are trusted so we override any user preferences for disabling
// javascript or images.
webkit_prefs->loads_images_automatically = true;
webkit_prefs->javascript_enabled = true;
// Tabs aren't typically allowed to close windows. But extensions shouldn't
// be subject to that.
webkit_prefs->allow_scripts_to_close_windows = true;
// Enable privileged WebGL extensions.
webkit_prefs->privileged_webgl_extensions_enabled = true;
// Disable anything that requires the GPU process for background pages.
// See http://crbug.com/64512 and http://crbug.com/64841.
if (render_view_type == chrome::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
webkit_prefs->experimental_webgl_enabled = false;
webkit_prefs->accelerated_compositing_enabled = false;
webkit_prefs->accelerated_2d_canvas_enabled = false;
}
}
}
} // extension_webkit_preferences
<commit_msg>Expose priviledged webgl extensions to hosted apps.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_webkit_preferences.h"
#include "chrome/common/extensions/extension.h"
#include "webkit/glue/webpreferences.h"
namespace extension_webkit_preferences {
void SetPreferences(const Extension* extension,
content::ViewType render_view_type,
WebPreferences* webkit_prefs) {
if (extension && !extension->is_hosted_app()) {
// Extensions are trusted so we override any user preferences for disabling
// javascript or images.
webkit_prefs->loads_images_automatically = true;
webkit_prefs->javascript_enabled = true;
// Tabs aren't typically allowed to close windows. But extensions shouldn't
// be subject to that.
webkit_prefs->allow_scripts_to_close_windows = true;
// Disable anything that requires the GPU process for background pages.
// See http://crbug.com/64512 and http://crbug.com/64841.
if (render_view_type == chrome::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
webkit_prefs->experimental_webgl_enabled = false;
webkit_prefs->accelerated_compositing_enabled = false;
webkit_prefs->accelerated_2d_canvas_enabled = false;
}
}
if (extension) {
// Enable WebGL features that regular pages can't access, since they add
// more risk of fingerprinting.
webkit_prefs->privileged_webgl_extensions_enabled = true;
}
}
} // extension_webkit_preferences
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webrequest_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "net/base/mock_host_resolver.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
namespace {
class CancelLoginDialog : public content::NotificationObserver {
public:
CancelLoginDialog() {
registrar_.Add(this,
chrome::NOTIFICATION_AUTH_NEEDED,
content::NotificationService::AllSources());
}
virtual ~CancelLoginDialog() {}
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
LoginHandler* handler =
content::Details<LoginNotificationDetails>(details).ptr()->handler();
handler->CancelAuth();
}
private:
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog);
};
} // namespace
class ExtensionWebRequestApiTest : public ExtensionApiTest {
public:
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionApiTest::SetUpInProcessBrowserTestFixture();
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
}
};
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
CancelLoginDialog login_dialog_helper;
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_auth_required.html")) <<
message_;
}
// Hangs flakily: http://crbug.com/91715
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
DISABLED_WebRequestBlocking) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_newTab.html"))
<< message_;
TabContents* tab = browser()->GetSelectedTabContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("newTab/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// There's a link on a.html with target=_blank. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Reenable ExtensionWebRequestApiTest.WebRequestBlocking after fixing the flakyness<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webrequest_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "net/base/mock_host_resolver.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
namespace {
class CancelLoginDialog : public content::NotificationObserver {
public:
CancelLoginDialog() {
registrar_.Add(this,
chrome::NOTIFICATION_AUTH_NEEDED,
content::NotificationService::AllSources());
}
virtual ~CancelLoginDialog() {}
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
LoginHandler* handler =
content::Details<LoginNotificationDetails>(details).ptr()->handler();
handler->CancelAuth();
}
private:
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog);
};
} // namespace
class ExtensionWebRequestApiTest : public ExtensionApiTest {
public:
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionApiTest::SetUpInProcessBrowserTestFixture();
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
}
};
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_api.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_simple.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_complex.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
CancelLoginDialog login_dialog_helper;
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_auth_required.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest,
WebRequestBlocking) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_blocking.html")) <<
message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalExtensionApis);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_newTab.html"))
<< message_;
TabContents* tab = browser()->GetSelectedTabContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("newTab/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// There's a link on a.html with target=_blank. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->render_view_host()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/chrome_url_request_context.h"
#include "base/command_line.h"
#include "base/format_macros.h"
#include "chrome/common/chrome_switches.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_config_service_common_unittest.h"
#include "testing/gtest/include/gtest/gtest.h"
// Builds an identifier for each test in an array.
#define TEST_DESC(desc) StringPrintf("at line %d <%s>", __LINE__, desc)
TEST(ChromeUrlRequestContextTest, CreateProxyConfigTest) {
FilePath unused_path(FILE_PATH_LITERAL("foo.exe"));
// Build the input command lines here.
CommandLine empty(unused_path);
CommandLine no_proxy(unused_path);
no_proxy.AppendSwitch(switches::kNoProxyServer);
CommandLine no_proxy_extra_params(unused_path);
no_proxy_extra_params.AppendSwitch(switches::kNoProxyServer);
no_proxy_extra_params.AppendSwitchWithValue(switches::kProxyServer,
L"http://proxy:8888");
CommandLine single_proxy(unused_path);
single_proxy.AppendSwitchWithValue(switches::kProxyServer,
L"http://proxy:8888");
CommandLine per_scheme_proxy(unused_path);
per_scheme_proxy.AppendSwitchWithValue(switches::kProxyServer,
L"http=httpproxy:8888;ftp=ftpproxy:8889");
CommandLine per_scheme_proxy_bypass(unused_path);
per_scheme_proxy_bypass.AppendSwitchWithValue(switches::kProxyServer,
L"http=httpproxy:8888;ftp=ftpproxy:8889");
per_scheme_proxy_bypass.AppendSwitchWithValue(
switches::kProxyBypassList,
L".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8");
CommandLine with_pac_url(unused_path);
with_pac_url.AppendSwitchWithValue(switches::kProxyPacUrl,
L"http://wpad/wpad.dat");
with_pac_url.AppendSwitchWithValue(
switches::kProxyBypassList,
L".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8");
CommandLine with_auto_detect(unused_path);
with_auto_detect.AppendSwitch(switches::kProxyAutoDetect);
// Inspired from proxy_config_service_win_unittest.cc.
const struct {
// Short description to identify the test
std::string description;
// The command line to build a ProxyConfig from.
const CommandLine& command_line;
// Expected outputs (fields of the ProxyConfig).
bool is_null;
bool auto_detect;
GURL pac_url;
net::ProxyRulesExpectation proxy_rules;
} tests[] = {
{
TEST_DESC("Empty command line"),
// Input
empty,
// Expected result
true, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
},
{
TEST_DESC("No proxy"),
// Input
no_proxy,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
},
{
TEST_DESC("No proxy with extra parameters."),
// Input
no_proxy_extra_params,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
},
{
TEST_DESC("Single proxy."),
// Input
single_proxy,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Single(
"proxy:8888", // single proxy
""), // bypass rules
},
{
TEST_DESC("Per scheme proxy."),
// Input
per_scheme_proxy,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::PerScheme(
"httpproxy:8888", // http
"", // https
"ftpproxy:8889", // ftp
""), // bypass rules
},
{
TEST_DESC("Per scheme proxy with bypass URLs."),
// Input
per_scheme_proxy_bypass,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::PerScheme(
"httpproxy:8888", // http
"", // https
"ftpproxy:8889", // ftp
"*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"),
},
{
TEST_DESC("Pac URL with proxy bypass URLs"),
// Input
with_pac_url,
// Expected result
false, // is_null
false, // auto_detect
GURL("http://wpad/wpad.dat"), // pac_url
net::ProxyRulesExpectation::EmptyWithBypass(
"*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"),
},
{
TEST_DESC("Autodetect"),
// Input
with_auto_detect,
// Expected result
false, // is_null
true, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
}
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
SCOPED_TRACE(StringPrintf("Test[%" PRIuS "] %s", i,
tests[i].description.c_str()));
scoped_ptr<net::ProxyConfig> config(CreateProxyConfig(
CommandLine(tests[i].command_line)));
if (tests[i].is_null) {
EXPECT_TRUE(config == NULL);
} else {
EXPECT_TRUE(config != NULL);
EXPECT_EQ(tests[i].auto_detect, config->auto_detect());
EXPECT_EQ(tests[i].pac_url, config->pac_url());
EXPECT_TRUE(tests[i].proxy_rules.Matches(config->proxy_rules()));
}
}
}
<commit_msg>Cleanup: Fix an innacurate test name.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/chrome_url_request_context.h"
#include "base/command_line.h"
#include "base/format_macros.h"
#include "chrome/common/chrome_switches.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_config_service_common_unittest.h"
#include "testing/gtest/include/gtest/gtest.h"
// Builds an identifier for each test in an array.
#define TEST_DESC(desc) StringPrintf("at line %d <%s>", __LINE__, desc)
TEST(ChromeURLRequestContextTest, CreateProxyConfigTest) {
FilePath unused_path(FILE_PATH_LITERAL("foo.exe"));
// Build the input command lines here.
CommandLine empty(unused_path);
CommandLine no_proxy(unused_path);
no_proxy.AppendSwitch(switches::kNoProxyServer);
CommandLine no_proxy_extra_params(unused_path);
no_proxy_extra_params.AppendSwitch(switches::kNoProxyServer);
no_proxy_extra_params.AppendSwitchWithValue(switches::kProxyServer,
L"http://proxy:8888");
CommandLine single_proxy(unused_path);
single_proxy.AppendSwitchWithValue(switches::kProxyServer,
L"http://proxy:8888");
CommandLine per_scheme_proxy(unused_path);
per_scheme_proxy.AppendSwitchWithValue(switches::kProxyServer,
L"http=httpproxy:8888;ftp=ftpproxy:8889");
CommandLine per_scheme_proxy_bypass(unused_path);
per_scheme_proxy_bypass.AppendSwitchWithValue(switches::kProxyServer,
L"http=httpproxy:8888;ftp=ftpproxy:8889");
per_scheme_proxy_bypass.AppendSwitchWithValue(
switches::kProxyBypassList,
L".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8");
CommandLine with_pac_url(unused_path);
with_pac_url.AppendSwitchWithValue(switches::kProxyPacUrl,
L"http://wpad/wpad.dat");
with_pac_url.AppendSwitchWithValue(
switches::kProxyBypassList,
L".google.com, foo.com:99, 1.2.3.4:22, 127.0.0.1/8");
CommandLine with_auto_detect(unused_path);
with_auto_detect.AppendSwitch(switches::kProxyAutoDetect);
// Inspired from proxy_config_service_win_unittest.cc.
const struct {
// Short description to identify the test
std::string description;
// The command line to build a ProxyConfig from.
const CommandLine& command_line;
// Expected outputs (fields of the ProxyConfig).
bool is_null;
bool auto_detect;
GURL pac_url;
net::ProxyRulesExpectation proxy_rules;
} tests[] = {
{
TEST_DESC("Empty command line"),
// Input
empty,
// Expected result
true, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
},
{
TEST_DESC("No proxy"),
// Input
no_proxy,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
},
{
TEST_DESC("No proxy with extra parameters."),
// Input
no_proxy_extra_params,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
},
{
TEST_DESC("Single proxy."),
// Input
single_proxy,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Single(
"proxy:8888", // single proxy
""), // bypass rules
},
{
TEST_DESC("Per scheme proxy."),
// Input
per_scheme_proxy,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::PerScheme(
"httpproxy:8888", // http
"", // https
"ftpproxy:8889", // ftp
""), // bypass rules
},
{
TEST_DESC("Per scheme proxy with bypass URLs."),
// Input
per_scheme_proxy_bypass,
// Expected result
false, // is_null
false, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::PerScheme(
"httpproxy:8888", // http
"", // https
"ftpproxy:8889", // ftp
"*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"),
},
{
TEST_DESC("Pac URL with proxy bypass URLs"),
// Input
with_pac_url,
// Expected result
false, // is_null
false, // auto_detect
GURL("http://wpad/wpad.dat"), // pac_url
net::ProxyRulesExpectation::EmptyWithBypass(
"*.google.com,foo.com:99,1.2.3.4:22,127.0.0.1/8"),
},
{
TEST_DESC("Autodetect"),
// Input
with_auto_detect,
// Expected result
false, // is_null
true, // auto_detect
GURL(), // pac_url
net::ProxyRulesExpectation::Empty(),
}
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
SCOPED_TRACE(StringPrintf("Test[%" PRIuS "] %s", i,
tests[i].description.c_str()));
scoped_ptr<net::ProxyConfig> config(CreateProxyConfig(
CommandLine(tests[i].command_line)));
if (tests[i].is_null) {
EXPECT_TRUE(config == NULL);
} else {
EXPECT_TRUE(config != NULL);
EXPECT_EQ(tests[i].auto_detect, config->auto_detect());
EXPECT_EQ(tests[i].pac_url, config->pac_url());
EXPECT_TRUE(tests[i].proxy_rules.Matches(config->proxy_rules()));
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Utils/ResponseUtils.h>
#include <Utils/TestUtils.h>
#include <hspp/Tasks/BasicTasks/CombatTask.h>
#include <hspp/Tasks/BasicTasks/InitAttackCountTask.h>
using namespace Hearthstonepp;
class CombatTester
{
public:
CombatTester()
: m_gen(CardClass::DRUID, CardClass::ROGUE),
m_agent(std::move(m_gen.player1), std::move(m_gen.player2)),
m_resp(m_agent),
m_combat(m_agent.GetTaskAgent())
{
// Do Nothing
}
std::tuple<Player&, Player&> GetPlayer()
{
return { m_agent.GetPlayer1(), m_agent.GetPlayer2() };
}
void Attack(size_t src, size_t dst, MetaData expected, bool init = false)
{
if (init)
{
m_init.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());
m_init.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1());
}
auto target = m_resp.Target(src, dst);
MetaData result =
m_combat.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());
EXPECT_EQ(result, expected);
TaskMeta meta = target.get();
EXPECT_EQ(meta.id, +TaskID::REQUIRE);
}
private:
TestUtils::PlayerGenerator m_gen;
GameAgent m_agent;
TestUtils::AutoResponder m_resp;
BasicTasks::CombatTask m_combat;
BasicTasks::InitAttackCountTask m_init;
};
TEST(CombatTask, GetTaskID)
{
TaskAgent agent;
BasicTasks::CombatTask combat(agent);
EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT);
}
TEST(CombatTask, CombatDefault)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card1 = TestUtils::GenerateMinionCard("minion1", 3, 6);
auto card2 = TestUtils::GenerateMinionCard("minion2", 5, 4);
player1.field.emplace_back(new Minion(card1));
player2.field.emplace_back(new Minion(card2));
tester.Attack(1, 0, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);
EXPECT_EQ(player2.hero->health,
player2.hero->maxHealth - player1.field[0]->attack);
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(1));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));
EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));
auto card3 = TestUtils::GenerateMinionCard("minion3", 5, 6);
auto card4 = TestUtils::GenerateMinionCard("minion4", 5, 4);
player1.field.emplace_back(new Minion(card3));
player2.field.emplace_back(new Minion(card4));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));
EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));
auto card5 = TestUtils::GenerateMinionCard("minion5", 5, 4);
player1.field[0]->attack = 1;
player2.field.emplace_back(new Minion(card5));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(3));
}
TEST(CombatTask, IndexOutOfRange)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion1", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
tester.Attack(1, 2, MetaData::COMBAT_DST_IDX_OUT_OF_RANGE, true);
tester.Attack(2, 1, MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE, true);
}
TEST(CombatTask, CombatTaunt)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion1", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field[1]->gameTags[+GameTag::TAUNT] = 1;
tester.Attack(1, 1, MetaData::COMBAT_FIELD_HAVE_TAUNT, true);
player2.field[1]->gameTags[+GameTag::TAUNT] = 0;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
}
TEST(CombatTask, CombatStealth)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field[0]->gameTags[+GameTag::STEALTH] = 1;
tester.Attack(1, 1, MetaData::COMBAT_TARGET_STEALTH, true);
player1.field[0]->gameTags[+GameTag::STEALTH] = 1;
player2.field[0]->gameTags[+GameTag::STEALTH] = 0;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->gameTags[+GameTag::STEALTH], 0);
}
TEST(CombatTask, CombatImmune)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field[0]->gameTags[+GameTag::IMMUNE] = 1;
tester.Attack(1, 1, MetaData::COMBAT_TARGET_IMMUNE, true);
}
TEST(CombatTask, CombatAttackCount)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);
player1.field[0]->gameTags[+GameTag::WINDFURY] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS);
tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);
}
TEST(CombatTask, CombatDivineShield)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player1.field[0]->gameTags[+GameTag::DIVINE_SHIELD] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));
player2.field[0]->gameTags[+GameTag::DIVINE_SHIELD] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));
}
TEST(CombatTask, Poisonous)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player1.field[0]->gameTags[+GameTag::POISONOUS] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));
EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));
player2.field.emplace_back(new Minion(card));
player1.field[0]->gameTags[+GameTag::POISONOUS] = 0;
player2.field[0]->gameTags[+GameTag::POISONOUS] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));
}
<commit_msg>test: Change ability test names to unify<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <Utils/ResponseUtils.h>
#include <Utils/TestUtils.h>
#include <hspp/Tasks/BasicTasks/CombatTask.h>
#include <hspp/Tasks/BasicTasks/InitAttackCountTask.h>
using namespace Hearthstonepp;
class CombatTester
{
public:
CombatTester()
: m_gen(CardClass::DRUID, CardClass::ROGUE),
m_agent(std::move(m_gen.player1), std::move(m_gen.player2)),
m_resp(m_agent),
m_combat(m_agent.GetTaskAgent())
{
// Do Nothing
}
std::tuple<Player&, Player&> GetPlayer()
{
return { m_agent.GetPlayer1(), m_agent.GetPlayer2() };
}
void Attack(size_t src, size_t dst, MetaData expected, bool init = false)
{
if (init)
{
m_init.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());
m_init.Run(m_agent.GetPlayer2(), m_agent.GetPlayer1());
}
auto target = m_resp.Target(src, dst);
MetaData result =
m_combat.Run(m_agent.GetPlayer1(), m_agent.GetPlayer2());
EXPECT_EQ(result, expected);
TaskMeta meta = target.get();
EXPECT_EQ(meta.id, +TaskID::REQUIRE);
}
private:
TestUtils::PlayerGenerator m_gen;
GameAgent m_agent;
TestUtils::AutoResponder m_resp;
BasicTasks::CombatTask m_combat;
BasicTasks::InitAttackCountTask m_init;
};
TEST(CombatTask, GetTaskID)
{
TaskAgent agent;
BasicTasks::CombatTask combat(agent);
EXPECT_EQ(combat.GetTaskID(), +TaskID::COMBAT);
}
TEST(CombatTask, Default)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card1 = TestUtils::GenerateMinionCard("minion1", 3, 6);
auto card2 = TestUtils::GenerateMinionCard("minion2", 5, 4);
player1.field.emplace_back(new Minion(card1));
player2.field.emplace_back(new Minion(card2));
tester.Attack(1, 0, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);
EXPECT_EQ(player2.hero->health,
player2.hero->maxHealth - player1.field[0]->attack);
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(1));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));
EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));
auto card3 = TestUtils::GenerateMinionCard("minion3", 5, 6);
auto card4 = TestUtils::GenerateMinionCard("minion4", 5, 4);
player1.field.emplace_back(new Minion(card3));
player2.field.emplace_back(new Minion(card4));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(1));
EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));
auto card5 = TestUtils::GenerateMinionCard("minion5", 5, 4);
player1.field[0]->attack = 1;
player2.field.emplace_back(new Minion(card5));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(3));
}
TEST(CombatTask, IndexOutOfRange)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion1", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
tester.Attack(1, 2, MetaData::COMBAT_DST_IDX_OUT_OF_RANGE, true);
tester.Attack(2, 1, MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE, true);
}
TEST(CombatTask, Taunt)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion1", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field[1]->gameTags[+GameTag::TAUNT] = 1;
tester.Attack(1, 1, MetaData::COMBAT_FIELD_HAVE_TAUNT, true);
player2.field[1]->gameTags[+GameTag::TAUNT] = 0;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
}
TEST(CombatTask, Stealth)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field[0]->gameTags[+GameTag::STEALTH] = 1;
tester.Attack(1, 1, MetaData::COMBAT_TARGET_STEALTH, true);
player1.field[0]->gameTags[+GameTag::STEALTH] = 1;
player2.field[0]->gameTags[+GameTag::STEALTH] = 0;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->gameTags[+GameTag::STEALTH], 0);
}
TEST(CombatTask, Immune)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player2.field[0]->gameTags[+GameTag::IMMUNE] = 1;
tester.Attack(1, 1, MetaData::COMBAT_TARGET_IMMUNE, true);
}
TEST(CombatTask, Windfury)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);
player1.field[0]->gameTags[+GameTag::WINDFURY] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS);
tester.Attack(1, 1, MetaData::COMBAT_ALREADY_ATTACKED);
}
TEST(CombatTask, DivineShield)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player1.field[0]->gameTags[+GameTag::DIVINE_SHIELD] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, player1.field[0]->maxHealth);
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));
player2.field[0]->gameTags[+GameTag::DIVINE_SHIELD] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));
}
TEST(CombatTask, Poisonous)
{
CombatTester tester;
auto [player1, player2] = tester.GetPlayer();
auto card = TestUtils::GenerateMinionCard("minion", 1, 10);
player1.field.emplace_back(new Minion(card));
player2.field.emplace_back(new Minion(card));
player1.field[0]->gameTags[+GameTag::POISONOUS] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field[0]->health, static_cast<size_t>(9));
EXPECT_EQ(player2.field.size(), static_cast<size_t>(0));
player2.field.emplace_back(new Minion(card));
player1.field[0]->gameTags[+GameTag::POISONOUS] = 0;
player2.field[0]->gameTags[+GameTag::POISONOUS] = 1;
tester.Attack(1, 1, MetaData::COMBAT_SUCCESS, true);
EXPECT_EQ(player1.field.size(), static_cast<size_t>(0));
EXPECT_EQ(player2.field[0]->health, static_cast<size_t>(9));
}
<|endoftext|>
|
<commit_before>/**
* @file perf_index.hpp
* @brief Performance tests on index.
* @author Paolo D'Apice
*/
#ifndef VIS_PERF_INDEX_HPP
#define VIS_PERF_INDEX_HPP
#include "descriptors_type.hpp"
#include "index.hpp"
#include "utils/timer.hpp"
#include <boost/array.hpp>
namespace perf {
/// Number of times a single test is executed.
static const int NUM_EXECUTIONS = 10;
/// Number of data samples.
static const std::array<size_t,4> NUM_DATA = { 1000, 10000, 100000, 1000000 };
/// Number of trees in the kd-forest.
static const std::array<size_t,4> NUM_TREES = { 1, 2, 4, 8 };
/// Number of neighbors returned by query.
static const std::array<size_t,5> NUM_NEIGHBORS = { 1, 5, 10, 20, 50 };
/// Max comparisons for ANN.
static const std::array<size_t,5> MAX_COMPARISONS = { 0, 1000000, 100000, 10000, 100 };
/// @brief Build index on given descriptors matrix.
std::vector<Timer::timestamp_t>
buildIndex(const arma::fmat& data, vis::DescriptorsType type, size_t numTrees = 1);
/// @brief Query index with given descriptors matrix.
std::vector<Timer::timestamp_t>
queryIndex(const vis::Index& index, const arma::fmat& data,
size_t neighbors = 15, size_t maxComparisons = 0);
} /* namespace perf */
#endif /* VIS_PERF_INDEX_HPP */
<commit_msg>Fixed wrong include<commit_after>/**
* @file perf_index.hpp
* @brief Performance tests on index.
* @author Paolo D'Apice
*/
#ifndef VIS_PERF_INDEX_HPP
#define VIS_PERF_INDEX_HPP
#include "descriptors_type.hpp"
#include "index.hpp"
#include "utils/timer.hpp"
#include <array>
namespace perf {
/// Number of times a single test is executed.
static const int NUM_EXECUTIONS = 10;
/// Number of data samples.
static const std::array<size_t,4> NUM_DATA = { 1000, 10000, 100000, 1000000 };
/// Number of trees in the kd-forest.
static const std::array<size_t,4> NUM_TREES = { 1, 2, 4, 8 };
/// Number of neighbors returned by query.
static const std::array<size_t,5> NUM_NEIGHBORS = { 1, 5, 10, 20, 50 };
/// Max comparisons for ANN.
static const std::array<size_t,5> MAX_COMPARISONS = { 0, 1000000, 100000, 10000, 100 };
/// @brief Build index on given descriptors matrix.
std::vector<Timer::timestamp_t>
buildIndex(const arma::fmat& data, vis::DescriptorsType type, size_t numTrees = 1);
/// @brief Query index with given descriptors matrix.
std::vector<Timer::timestamp_t>
queryIndex(const vis::Index& index, const arma::fmat& data,
size_t neighbors = 15, size_t maxComparisons = 0);
} /* namespace perf */
#endif /* VIS_PERF_INDEX_HPP */
<|endoftext|>
|
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: geom/prep/AbstractPreparedPolygonContains.java r388 (JTS-1.12)
*
**********************************************************************/
#include <geos/geom/prep/AbstractPreparedPolygonContains.h>
#include <geos/geom/prep/PreparedPolygon.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/noding/SegmentString.h>
#include <geos/noding/SegmentStringUtil.h>
#include <geos/noding/SegmentIntersectionDetector.h>
#include <geos/noding/FastSegmentSetIntersectionFinder.h>
#include <geos/algorithm/LineIntersector.h>
// std
#include <cstddef>
namespace geos {
namespace geom { // geos::geom
namespace prep { // geos::geom::prep
//
// private:
//
bool
AbstractPreparedPolygonContains::isProperIntersectionImpliesNotContainedSituation(const geom::Geometry* testGeom)
{
// If the test geometry is polygonal we have the A/A situation.
// In this case, a proper intersection indicates that
// the Epsilon-Neighbourhood Exterior Intersection condition exists.
// This condition means that in some small
// area around the intersection point, there must exist a situation
// where the interior of the test intersects the exterior of the target.
// This implies the test is NOT contained in the target.
if(testGeom->getGeometryTypeId() == geos::geom::GEOS_MULTIPOLYGON
|| testGeom->getGeometryTypeId() == geos::geom::GEOS_POLYGON) {
return true;
}
// A single shell with no holes allows concluding that
// a proper intersection implies not contained
// (due to the Epsilon-Neighbourhood Exterior Intersection condition)
if(isSingleShell(prepPoly->getGeometry())) {
return true;
}
return false;
}
bool
AbstractPreparedPolygonContains::isSingleShell(const geom::Geometry& geom)
{
// handles single-element MultiPolygons, as well as Polygons
if(geom.getNumGeometries() != 1) {
return false;
}
const geom::Geometry* g = geom.getGeometryN(0);
const geom::Polygon* poly = dynamic_cast<const Polygon*>(g);
assert(poly);
std::size_t numHoles = poly->getNumInteriorRing();
return (0 == numHoles);
}
void
AbstractPreparedPolygonContains::findAndClassifyIntersections(const geom::Geometry* geom)
{
noding::SegmentString::ConstVect lineSegStr;
noding::SegmentStringUtil::extractSegmentStrings(geom, lineSegStr);
algorithm::LineIntersector li;
noding::SegmentIntersectionDetector intDetector(&li);
intDetector.setFindAllIntersectionTypes(true);
prepPoly->getIntersectionFinder()->intersects(&lineSegStr, &intDetector);
hasSegmentIntersection = intDetector.hasIntersection();
hasProperIntersection = intDetector.hasProperIntersection();
hasNonProperIntersection = intDetector.hasNonProperIntersection();
for(std::size_t i = 0, ni = lineSegStr.size(); i < ni; i++) {
delete lineSegStr[i];
}
}
//
// protected:
//
bool
AbstractPreparedPolygonContains::eval(const geom::Geometry* geom)
{
// Do point-in-poly tests first, since they are cheaper and may result
// in a quick negative result.
//
// If a point of any test components does not lie in target,
// result is false
bool isAllInTargetArea = isAllTestComponentsInTarget(geom);
if(!isAllInTargetArea) {
return false;
}
// If the test geometry consists of only Points,
// then it is now sufficient to test if any of those
// points lie in the interior of the target geometry.
// If so, the test is contained.
// If not, all points are on the boundary of the area,
// which implies not contained.
if(requireSomePointInInterior && geom->getDimension() == 0) {
bool isAnyInTargetInterior = isAnyTestComponentInTargetInterior(geom);
return isAnyInTargetInterior;
}
// Check if there is any intersection between the line segments
// in target and test.
// In some important cases, finding a proper interesection implies that the
// test geometry is NOT contained.
// These cases are:
// - If the test geometry is polygonal
// - If the target geometry is a single polygon with no holes
// In both of these cases, a proper intersection implies that there
// is some portion of the interior of the test geometry lying outside
// the target, which means that the test is not contained.
bool properIntersectionImpliesNotContained = isProperIntersectionImpliesNotContainedSituation(geom);
// find all intersection types which exist
findAndClassifyIntersections(geom);
if(properIntersectionImpliesNotContained && hasProperIntersection) {
return false;
}
// If all intersections are proper
// (i.e. no non-proper intersections occur)
// we can conclude that the test geometry is not contained in the target area,
// by the Epsilon-Neighbourhood Exterior Intersection condition.
// In real-world data this is likely to be by far the most common situation,
// since natural data is unlikely to have many exact vertex segment intersections.
// Thus this check is very worthwhile, since it avoid having to perform
// a full topological check.
//
// (If non-proper (vertex) intersections ARE found, this may indicate
// a situation where two shells touch at a single vertex, which admits
// the case where a line could cross between the shells and still be wholely contained in them.
if(hasSegmentIntersection && !hasNonProperIntersection) {
return false;
}
// If there is a segment intersection and the situation is not one
// of the ones above, the only choice is to compute the full topological
// relationship. This is because contains/covers is very sensitive
// to the situation along the boundary of the target.
if(hasSegmentIntersection) {
return fullTopologicalPredicate(geom);
}
// This tests for the case where a ring of the target lies inside
// a test polygon - which implies the exterior of the Target
// intersects the interior of the Test, and hence the result is false
if(geom->getGeometryTypeId() == geos::geom::GEOS_MULTIPOLYGON
|| geom->getGeometryTypeId() == geos::geom::GEOS_POLYGON) {
// TODO: generalize this to handle GeometryCollections
bool isTargetInTestArea = isAnyTargetComponentInAreaTest(geom, prepPoly->getRepresentativePoints());
if(isTargetInTestArea) {
return false;
}
}
return true;
}
//
// public:
//
} // geos::geom::prep
} // geos::geom
} // geos
<commit_msg>Avoid double-testing all positive PIP results in AbstractPreparedPolygonContains<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: geom/prep/AbstractPreparedPolygonContains.java r388 (JTS-1.12)
*
**********************************************************************/
#include <geos/geom/prep/AbstractPreparedPolygonContains.h>
#include <geos/geom/prep/PreparedPolygon.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/noding/SegmentString.h>
#include <geos/noding/SegmentStringUtil.h>
#include <geos/noding/SegmentIntersectionDetector.h>
#include <geos/noding/FastSegmentSetIntersectionFinder.h>
#include <geos/algorithm/LineIntersector.h>
// std
#include <cstddef>
namespace geos {
namespace geom { // geos::geom
namespace prep { // geos::geom::prep
//
// private:
//
bool
AbstractPreparedPolygonContains::isProperIntersectionImpliesNotContainedSituation(const geom::Geometry* testGeom)
{
// If the test geometry is polygonal we have the A/A situation.
// In this case, a proper intersection indicates that
// the Epsilon-Neighbourhood Exterior Intersection condition exists.
// This condition means that in some small
// area around the intersection point, there must exist a situation
// where the interior of the test intersects the exterior of the target.
// This implies the test is NOT contained in the target.
if(testGeom->getGeometryTypeId() == geos::geom::GEOS_MULTIPOLYGON
|| testGeom->getGeometryTypeId() == geos::geom::GEOS_POLYGON) {
return true;
}
// A single shell with no holes allows concluding that
// a proper intersection implies not contained
// (due to the Epsilon-Neighbourhood Exterior Intersection condition)
if(isSingleShell(prepPoly->getGeometry())) {
return true;
}
return false;
}
bool
AbstractPreparedPolygonContains::isSingleShell(const geom::Geometry& geom)
{
// handles single-element MultiPolygons, as well as Polygons
if(geom.getNumGeometries() != 1) {
return false;
}
const geom::Geometry* g = geom.getGeometryN(0);
const geom::Polygon* poly = dynamic_cast<const Polygon*>(g);
assert(poly);
std::size_t numHoles = poly->getNumInteriorRing();
return (0 == numHoles);
}
void
AbstractPreparedPolygonContains::findAndClassifyIntersections(const geom::Geometry* geom)
{
noding::SegmentString::ConstVect lineSegStr;
noding::SegmentStringUtil::extractSegmentStrings(geom, lineSegStr);
algorithm::LineIntersector li;
noding::SegmentIntersectionDetector intDetector(&li);
intDetector.setFindAllIntersectionTypes(true);
prepPoly->getIntersectionFinder()->intersects(&lineSegStr, &intDetector);
hasSegmentIntersection = intDetector.hasIntersection();
hasProperIntersection = intDetector.hasProperIntersection();
hasNonProperIntersection = intDetector.hasNonProperIntersection();
for(std::size_t i = 0, ni = lineSegStr.size(); i < ni; i++) {
delete lineSegStr[i];
}
}
//
// protected:
//
bool
AbstractPreparedPolygonContains::eval(const geom::Geometry* geom)
{
// Do point-in-poly tests first, since they are cheaper and may result
// in a quick negative result.
//
// If a point of any test components does not lie in target,
// result is false
if (!requireSomePointInInterior || geom->getGeometryTypeId() != GEOS_POINT) {
bool isAllInTargetArea = isAllTestComponentsInTarget(geom);
if (!isAllInTargetArea) {
return false;
}
}
// If the test geometry consists of only Points,
// then it is now sufficient to test if any of those
// points lie in the interior of the target geometry.
// If so, the test is contained.
// If not, all points are on the boundary of the area,
// which implies not contained.
if(requireSomePointInInterior && geom->getDimension() == 0) {
bool isAnyInTargetInterior = isAnyTestComponentInTargetInterior(geom);
return isAnyInTargetInterior;
}
// Check if there is any intersection between the line segments
// in target and test.
// In some important cases, finding a proper interesection implies that the
// test geometry is NOT contained.
// These cases are:
// - If the test geometry is polygonal
// - If the target geometry is a single polygon with no holes
// In both of these cases, a proper intersection implies that there
// is some portion of the interior of the test geometry lying outside
// the target, which means that the test is not contained.
bool properIntersectionImpliesNotContained = isProperIntersectionImpliesNotContainedSituation(geom);
// find all intersection types which exist
findAndClassifyIntersections(geom);
if(properIntersectionImpliesNotContained && hasProperIntersection) {
return false;
}
// If all intersections are proper
// (i.e. no non-proper intersections occur)
// we can conclude that the test geometry is not contained in the target area,
// by the Epsilon-Neighbourhood Exterior Intersection condition.
// In real-world data this is likely to be by far the most common situation,
// since natural data is unlikely to have many exact vertex segment intersections.
// Thus this check is very worthwhile, since it avoid having to perform
// a full topological check.
//
// (If non-proper (vertex) intersections ARE found, this may indicate
// a situation where two shells touch at a single vertex, which admits
// the case where a line could cross between the shells and still be wholely contained in them.
if(hasSegmentIntersection && !hasNonProperIntersection) {
return false;
}
// If there is a segment intersection and the situation is not one
// of the ones above, the only choice is to compute the full topological
// relationship. This is because contains/covers is very sensitive
// to the situation along the boundary of the target.
if(hasSegmentIntersection) {
return fullTopologicalPredicate(geom);
}
// This tests for the case where a ring of the target lies inside
// a test polygon - which implies the exterior of the Target
// intersects the interior of the Test, and hence the result is false
if(geom->getGeometryTypeId() == geos::geom::GEOS_MULTIPOLYGON
|| geom->getGeometryTypeId() == geos::geom::GEOS_POLYGON) {
// TODO: generalize this to handle GeometryCollections
bool isTargetInTestArea = isAnyTargetComponentInAreaTest(geom, prepPoly->getRepresentativePoints());
if(isTargetInTestArea) {
return false;
}
}
return true;
}
//
// public:
//
} // geos::geom::prep
} // geos::geom
} // geos
<|endoftext|>
|
<commit_before>
#include <DuiLocale>
#include <QTimer>
#include <QHash>
#include <QObject>
#include <QDebug>
#include <QDBusInterface>
#include <QAbstractEventDispatcher>
#include <DuiInfoBanner>
#include "notifier.h"
#include "sysuid.h"
#include "notifierdbusadaptor.h"
NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, unsigned int notifId) :
QObject(QAbstractEventDispatcher::instance()),
notifId(notifId),
notification(NULL)
{
connect(this, SIGNAL(timeout(unsigned int)), receiver, member);
timerId = startTimer(expireTimeout);
}
NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, DuiInfoBanner* notification) :
QObject(QAbstractEventDispatcher::instance()),
notifId(-1),
notification(notification)
{
connect(this, SIGNAL(timeout(DuiInfoBanner*)), receiver, member);
connect(notification, SIGNAL(buttonClicked()), this, SLOT(doKillTimer()));
connect(notification, SIGNAL(clicked()), this, SLOT(doKillTimer()));
timerId = startTimer(expireTimeout);
}
NotifTimer::~NotifTimer()
{
if (timerId > 0)
killTimer(timerId);
}
void NotifTimer::timerEvent(QTimerEvent *e)
{
// need to kill the timer _before_ we emit timeout() in case the
// slot connected to timeout calls processEvents()
doKillTimer();
emit timeout(notification);
emit timeout(notifId);
delete this;
}
void NotifTimer::doKillTimer()
{
if (timerId > 0)
killTimer(timerId);
timerId = -1;
}
// TODO.: Use the logical names when available
// In the future the notifier connects to Notification Framework API and uses that to create notifications
// See messge formats from af/duihome:home/notifications/notificationmanager.xml;
// example message to test notificationManager:
// dbus-send --print-reply --dest=org.maemo.dui.NotificationManager / org.maemo.dui.NotificationManager.addNotification uint32:0 string:'new-message' string:'Message received' string:'Hello DUI' string:'link' string:'Icon-close'
Notifier::Notifier(QObject* parent) :
QObject(parent)
{
dbus = new NotifierDBusAdaptor();
managerIf = new QDBusInterface ( "org.maemo.dui.NotificationManager", "/", "org.maemo.dui.NotificationManager");
}
Notifier::~Notifier()
{
if(NULL != dbus)
delete dbus;
dbus = NULL;
delete managerIf;
managerIf = NULL;
}
QObject* Notifier::responseObject()
{
return (QObject*)dbus;
}
void Notifier::showNotification(const QString ¬ifText, NotificationType::Type type)
{
switch (type)
{
case NotificationType::error:
showDBusNotification(notifText, QString("error"));
break;
case NotificationType::warning:
showDBusNotification(notifText, QString("warning"));
break;
case NotificationType::info:
showDBusNotification(notifText, QString("info"));
break;
}
}
void Notifier::showConfirmation(const QString ¬ifText, const QString &buttonText)
{
/*
// from DuiRemoteAction:
QStringList l = string.split(' ');
if (l.count() > 3) {
d->serviceName = l.at(0);
d->objectPath = l.at(1);
d->interface = l.at(2);
d->methodName = l.at(3);
}
*/
QString action(Sysuid::dbusService() + " " + Sysuid::dbusPath() + " " + NotifierDBusAdaptor::dbusInterfaceName() + " ");
if (trid("qtn_cell_continue", "Continue") == buttonText)
action += "pinQueryCancel";
else if (trid("qtn_cell_try_again", "Try again") == buttonText)
action += "simLockRetry";
qDebug() << Q_FUNC_INFO << "action:" << action;
showDBusNotification(notifText, QString("confirmation"), QString(""), 0, action, buttonText);
}
void Notifier::notificationTimeout(unsigned int notifId)
{
if(0 < notifId) {
removeNotification(notifId);
}
}
void Notifier::notificationTimeout(DuiInfoBanner* notif)
{
qDebug() << Q_FUNC_INFO << "notif:" << (QObject*)notif;
if (notif != NULL) {
notif->disappear();
}
}
void Notifier::removeNotification(unsigned int id)
{
QDBusMessage reply = managerIf->call(
QString("removeNotification"),
QVariant((unsigned int)id));
// practically just debugging...
if(reply.type() == QDBusMessage::ErrorMessage) {
qDebug() << Q_FUNC_INFO << "(" << id << ") error reply:" << reply.errorName();
}
else if(reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() > 0) {
qDebug() << Q_FUNC_INFO << "(" << id << ") result:" << reply.arguments()[0].toUInt();
}
else {
qDebug() << Q_FUNC_INFO << "(" << id << ") reply type:" << reply.type();
}
}
void Notifier::showDBusNotification(QString notifText, QString evetType, QString summary, int expireTimeout, QString action, QString buttonText)
{
QDBusMessage reply = managerIf->call(
QString("addNotification"),
QVariant((unsigned int)0),
QVariant(evetType), // temporary; correct types not specified yet; always shows envelope in info banner.
QVariant(summary),
QVariant(notifText),
QVariant(action),
QVariant(QString("Icon-close")));
if(reply.type() == QDBusMessage::ErrorMessage) {
qDebug() << Q_FUNC_INFO << " error reply:" << reply.errorName();
// because of bootup order, connection can't be done in constructor.
bool res = connect(
dbus, SIGNAL(showNotification(QString, NotificationType)),
this, SLOT(showNotification(QString, NotificationType)));
if(!res){
showLocalNotification(expireTimeout, notifText, buttonText);
}
}
else if(reply.type() == QDBusMessage::ReplyMessage)
{
unsigned int notifId(0);
QList<QVariant> args = reply.arguments();
if(args.count() >= 1)
{
notifId = args[0].toUInt();
qDebug() << Q_FUNC_INFO << ": notifId:" << notifId << "msg:" << notifText;
}
notifTimer(expireTimeout, notifId);
}
else {
qDebug() << Q_FUNC_INFO << "reply type:" << reply.type();
}
}
void Notifier::notifTimer(int expireTimeout, unsigned int notifId)
{
if(0 < expireTimeout){
(void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(unsigned int)), notifId);
}
}
void Notifier::notifTimer(int expireTimeout, DuiInfoBanner* notif)
{
qDebug() << Q_FUNC_INFO << "expireTimeout:" << expireTimeout;
if(!notif){
return;
}
if(0 < expireTimeout){
(void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(DuiInfoBanner*)), notif);
}
else if(0 >= notif->buttonText().length()){
notif->disappear();
}
}
void Notifier::showLocalNotification(int expireTimeout, QString notifText, QString buttonText)
{
qDebug() << Q_FUNC_INFO << notifText;
// DuiInfoBanner(BannerType type, const QString& image, const QString& body, const QString& iconId);
DuiInfoBanner* n = new DuiInfoBanner(DuiInfoBanner::Information,
"Icon-close",
QString(notifText),
"Icon-close");
if (trid("qtn_cell_continue", "Continue") == buttonText){
expireTimeout = 0;
n->setButtonText(buttonText);
connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationPinQueryCancel()));
}
else if (trid("qtn_cell_try_again", "Try again") == buttonText){
expireTimeout = 0;
n->setButtonText(buttonText);
connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationSimLockRetry()));
}
connect(n, SIGNAL(clicked()), this, SLOT(localNotificationClose()));
n->appear(DuiSceneWindow::DestroyWhenDone);
notifTimer(expireTimeout, n);
}
void Notifier::localNotificationClose()
{
DuiInfoBanner *ib = qobject_cast<DuiInfoBanner *>(sender());
qDebug() << Q_FUNC_INFO << (QObject*) ib;
if (ib != NULL) {
ib->disappear();
}
}
void Notifier::localNotificationPinQueryCancel()
{
localNotificationClose();
dbus->pinQueryCancel();
}
void Notifier::localNotificationSimLockRetry()
{
localNotificationClose();
dbus->simLockRetry();
}
<commit_msg>Unused parameter removed.<commit_after>
#include <DuiLocale>
#include <QTimer>
#include <QHash>
#include <QObject>
#include <QDebug>
#include <QDBusInterface>
#include <QAbstractEventDispatcher>
#include <DuiInfoBanner>
#include "notifier.h"
#include "sysuid.h"
#include "notifierdbusadaptor.h"
NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, unsigned int notifId) :
QObject(QAbstractEventDispatcher::instance()),
notifId(notifId),
notification(NULL)
{
connect(this, SIGNAL(timeout(unsigned int)), receiver, member);
timerId = startTimer(expireTimeout);
}
NotifTimer::NotifTimer(int expireTimeout, QObject *receiver, const char *member, DuiInfoBanner* notification) :
QObject(QAbstractEventDispatcher::instance()),
notifId(-1),
notification(notification)
{
connect(this, SIGNAL(timeout(DuiInfoBanner*)), receiver, member);
connect(notification, SIGNAL(buttonClicked()), this, SLOT(doKillTimer()));
connect(notification, SIGNAL(clicked()), this, SLOT(doKillTimer()));
timerId = startTimer(expireTimeout);
}
NotifTimer::~NotifTimer()
{
if (timerId > 0)
killTimer(timerId);
}
void NotifTimer::timerEvent(QTimerEvent *)
{
// need to kill the timer _before_ we emit timeout() in case the
// slot connected to timeout calls processEvents()
doKillTimer();
emit timeout(notification);
emit timeout(notifId);
delete this;
}
void NotifTimer::doKillTimer()
{
if (timerId > 0)
killTimer(timerId);
timerId = -1;
}
// TODO.: Use the logical names when available
// In the future the notifier connects to Notification Framework API and uses that to create notifications
// See messge formats from af/duihome:home/notifications/notificationmanager.xml;
// example message to test notificationManager:
// dbus-send --print-reply --dest=org.maemo.dui.NotificationManager / org.maemo.dui.NotificationManager.addNotification uint32:0 string:'new-message' string:'Message received' string:'Hello DUI' string:'link' string:'Icon-close'
Notifier::Notifier(QObject* parent) :
QObject(parent)
{
dbus = new NotifierDBusAdaptor();
managerIf = new QDBusInterface ( "org.maemo.dui.NotificationManager", "/", "org.maemo.dui.NotificationManager");
}
Notifier::~Notifier()
{
if(NULL != dbus)
delete dbus;
dbus = NULL;
delete managerIf;
managerIf = NULL;
}
QObject* Notifier::responseObject()
{
return (QObject*)dbus;
}
void Notifier::showNotification(const QString ¬ifText, NotificationType::Type type)
{
switch (type)
{
case NotificationType::error:
showDBusNotification(notifText, QString("error"));
break;
case NotificationType::warning:
showDBusNotification(notifText, QString("warning"));
break;
case NotificationType::info:
showDBusNotification(notifText, QString("info"));
break;
}
}
void Notifier::showConfirmation(const QString ¬ifText, const QString &buttonText)
{
/*
// from DuiRemoteAction:
QStringList l = string.split(' ');
if (l.count() > 3) {
d->serviceName = l.at(0);
d->objectPath = l.at(1);
d->interface = l.at(2);
d->methodName = l.at(3);
}
*/
QString action(Sysuid::dbusService() + " " + Sysuid::dbusPath() + " " + NotifierDBusAdaptor::dbusInterfaceName() + " ");
if (trid("qtn_cell_continue", "Continue") == buttonText)
action += "pinQueryCancel";
else if (trid("qtn_cell_try_again", "Try again") == buttonText)
action += "simLockRetry";
qDebug() << Q_FUNC_INFO << "action:" << action;
showDBusNotification(notifText, QString("confirmation"), QString(""), 0, action, buttonText);
}
void Notifier::notificationTimeout(unsigned int notifId)
{
if(0 < notifId) {
removeNotification(notifId);
}
}
void Notifier::notificationTimeout(DuiInfoBanner* notif)
{
qDebug() << Q_FUNC_INFO << "notif:" << (QObject*)notif;
if (notif != NULL) {
notif->disappear();
}
}
void Notifier::removeNotification(unsigned int id)
{
QDBusMessage reply = managerIf->call(
QString("removeNotification"),
QVariant((unsigned int)id));
// practically just debugging...
if(reply.type() == QDBusMessage::ErrorMessage) {
qDebug() << Q_FUNC_INFO << "(" << id << ") error reply:" << reply.errorName();
}
else if(reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() > 0) {
qDebug() << Q_FUNC_INFO << "(" << id << ") result:" << reply.arguments()[0].toUInt();
}
else {
qDebug() << Q_FUNC_INFO << "(" << id << ") reply type:" << reply.type();
}
}
void Notifier::showDBusNotification(QString notifText, QString evetType, QString summary, int expireTimeout, QString action, QString buttonText)
{
QDBusMessage reply = managerIf->call(
QString("addNotification"),
QVariant((unsigned int)0),
QVariant(evetType), // temporary; correct types not specified yet; always shows envelope in info banner.
QVariant(summary),
QVariant(notifText),
QVariant(action),
QVariant(QString("Icon-close")));
if(reply.type() == QDBusMessage::ErrorMessage) {
qDebug() << Q_FUNC_INFO << " error reply:" << reply.errorName();
// because of bootup order, connection can't be done in constructor.
bool res = connect(
dbus, SIGNAL(showNotification(QString, NotificationType)),
this, SLOT(showNotification(QString, NotificationType)));
if(!res){
showLocalNotification(expireTimeout, notifText, buttonText);
}
}
else if(reply.type() == QDBusMessage::ReplyMessage)
{
unsigned int notifId(0);
QList<QVariant> args = reply.arguments();
if(args.count() >= 1)
{
notifId = args[0].toUInt();
qDebug() << Q_FUNC_INFO << ": notifId:" << notifId << "msg:" << notifText;
}
notifTimer(expireTimeout, notifId);
}
else {
qDebug() << Q_FUNC_INFO << "reply type:" << reply.type();
}
}
void Notifier::notifTimer(int expireTimeout, unsigned int notifId)
{
if(0 < expireTimeout){
(void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(unsigned int)), notifId);
}
}
void Notifier::notifTimer(int expireTimeout, DuiInfoBanner* notif)
{
qDebug() << Q_FUNC_INFO << "expireTimeout:" << expireTimeout;
if(!notif){
return;
}
if(0 < expireTimeout){
(void) new NotifTimer(expireTimeout, this, SLOT(notificationTimeout(DuiInfoBanner*)), notif);
}
else if(0 >= notif->buttonText().length()){
notif->disappear();
}
}
void Notifier::showLocalNotification(int expireTimeout, QString notifText, QString buttonText)
{
qDebug() << Q_FUNC_INFO << notifText;
// DuiInfoBanner(BannerType type, const QString& image, const QString& body, const QString& iconId);
DuiInfoBanner* n = new DuiInfoBanner(DuiInfoBanner::Information,
"Icon-close",
QString(notifText),
"Icon-close");
if (trid("qtn_cell_continue", "Continue") == buttonText){
expireTimeout = 0;
n->setButtonText(buttonText);
connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationPinQueryCancel()));
}
else if (trid("qtn_cell_try_again", "Try again") == buttonText){
expireTimeout = 0;
n->setButtonText(buttonText);
connect(n, SIGNAL(buttonClicked()), this, SLOT(localNotificationSimLockRetry()));
}
connect(n, SIGNAL(clicked()), this, SLOT(localNotificationClose()));
n->appear(DuiSceneWindow::DestroyWhenDone);
notifTimer(expireTimeout, n);
}
void Notifier::localNotificationClose()
{
DuiInfoBanner *ib = qobject_cast<DuiInfoBanner *>(sender());
qDebug() << Q_FUNC_INFO << (QObject*) ib;
if (ib != NULL) {
ib->disappear();
}
}
void Notifier::localNotificationPinQueryCancel()
{
localNotificationClose();
dbus->pinQueryCancel();
}
void Notifier::localNotificationSimLockRetry()
{
localNotificationClose();
dbus->simLockRetry();
}
<|endoftext|>
|
<commit_before>#include "numerics.h"
using namespace std;
namespace numerics {
// subtract minimum value, logaddexp residuals, pass residuals and partition to
// draw_sample_with_partition
int draw_sample_unnormalized(vector<double> unorm_logps, double rand_u) {
double max_el = *std::max_element(unorm_logps.begin(), unorm_logps.end());
double partition = 0;
vector<double>::iterator it = unorm_logps.begin();
for(; it!=unorm_logps.end(); it++) {
*it -= max_el;
partition += exp(*it);
}
double log_partition = log(partition);
int draw = draw_sample_with_partition(unorm_logps, log_partition,
rand_u);
return draw;
}
int draw_sample_with_partition(vector<double> unorm_logps,
double log_partition, double rand_u) {
int draw = 0;
vector<double>::iterator it = unorm_logps.begin();
for(; it!=unorm_logps.end(); it++) {
rand_u -= exp(*it - log_partition);
if(rand_u < 0) {
return draw;
}
draw++;
}
// FIXME: should this fail?
assert(rand_u < 1E-10);
return draw;
}
// draw_sample_with_partition w/o exp() of ratio and no test for p(last)
// only useful for crp_init or supercluster swapping since no data component
int crp_draw_sample(vector<int> counts, int sum_counts, double alpha,
double rand_u) {
int draw = 0;
double partition = sum_counts + alpha;
vector<int>::iterator it = counts.begin();
for(; it!=counts.end(); it++) {
rand_u -= (*it / partition);
if(rand_u <0) {
return draw;
}
draw++;
}
// new cluster
return draw;
}
// p(alpha | clusters)
double calc_crp_alpha_conditional(std::vector<int> counts,
double alpha, int sum_counts,
bool absolute) {
int num_clusters = counts.size();
if(sum_counts==-1) {
sum_counts = std::accumulate(counts.begin(), counts.end(), 0);
}
double logp = lgamma(alpha) \
+ num_clusters * log(alpha) \
- lgamma(alpha + sum_counts);
// absolute necessary for determining true distribution rather than relative
if(absolute) {
double sum_log_gammas = 0;
std::vector<int>::iterator it = counts.begin();
for(; it!=counts.end(); it++) {
sum_log_gammas += lgamma(*it);
}
logp += sum_log_gammas;
}
return logp;
}
// helper for may calls to calc_crp_alpha_conditional
std::vector<double> calc_crp_alpha_conditionals(std::vector<double> grid,
std::vector<int> counts,
bool absolute) {
int sum_counts = std::accumulate(counts.begin(), counts.end(), 0);
std::vector<double> logps;
std::vector<double>::iterator it = grid.begin();
for(; it!=grid.end(); it++) {
double alpha = *it;
double logp = calc_crp_alpha_conditional(counts, alpha,
sum_counts, absolute);
logps.push_back(logp);
}
// note: prior distribution must still be added
return logps;
}
// p(z=cluster | alpha, clusters)
double calc_cluster_crp_logp(double cluster_weight, double sum_weights,
double alpha) {
if(cluster_weight == 0) {
cluster_weight = alpha;
}
double log_numerator = log(cluster_weight);
// presumes data has already been removed from the model
double log_denominator = log(sum_weights + alpha);
double log_probability = log_numerator - log_denominator;
return log_probability;
}
void insert_to_continuous_suffstats(int &count,
double &sum_x, double &sum_x_sq,
double el) {
count += 1;
sum_x += el;
sum_x_sq += el * el;
}
void remove_from_continuous_suffstats(int &count,
double &sum_x, double &sum_x_sq,
double el) {
count -= 1;
sum_x -= el;
sum_x_sq -= el * el;
}
/*
r' = r + n
nu' = nu + n
m' = m + (X-nm)/(r+n)
s' = s + C + rm**2 - r'm'**2
*/
void update_continuous_hypers(int count,
double sum_x, double sum_x_sq,
double &r, double &nu,
double &s, double &mu) {
double r_prime = r + count;
double nu_prime = nu + count;
double mu_prime = ((r * mu) + sum_x) / r_prime;
double s_prime = s + sum_x_sq \
+ (r * mu * mu) \
- (r_prime * mu_prime * mu_prime);
//
r = r_prime;
nu = nu_prime;
s = s_prime;
mu = mu_prime;
}
double calc_continuous_log_Z(double r, double nu, double s) {
double nu_over_2 = .5 * nu;
return nu_over_2 * (LOG_2 - log(s)) \
+ HALF_LOG_2PI \
- .5 * log(r) \
+ lgamma(nu_over_2);
}
double calc_continuous_logp(int count,
double r, double nu,
double s,
double log_Z_0) {
return -count * HALF_LOG_2PI + calc_continuous_log_Z(r, nu, s) - log_Z_0;
}
double calc_continuous_data_logp(int count,
double sum_x, double sum_x_sq,
double r, double nu,
double s, double mu,
double el,
double score_0) {
insert_to_continuous_suffstats(count, sum_x, sum_x_sq, el);
update_continuous_hypers(count, sum_x, sum_x_sq, r, nu, s, mu);
double logp = calc_continuous_logp(count, r, nu, s, score_0);
return logp;
}
vector<double> calc_continuous_r_conditionals(std::vector<double> r_grid,
int count,
double sum_x,
double sum_x_sq,
double nu,
double s,
double mu) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=r_grid.begin(); it!=r_grid.end(); it++) {
double r_prime = *it;
double nu_prime = nu;
double s_prime = s;
double mu_prime = mu;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logp += -log(r_prime);
logps.push_back(logp);
}
return logps;
}
vector<double> calc_continuous_nu_conditionals(std::vector<double> nu_grid,
int count,
double sum_x,
double sum_x_sq,
double r,
double s,
double mu) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=nu_grid.begin(); it!=nu_grid.end(); it++) {
double r_prime = r;
double nu_prime = *it;
double s_prime = s;
double mu_prime = mu;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logp += -log(nu_prime);
logps.push_back(logp);
}
return logps;
}
vector<double> calc_continuous_s_conditionals(std::vector<double> s_grid,
int count,
double sum_x,
double sum_x_sq,
double r,
double nu,
double mu) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=s_grid.begin(); it!=s_grid.end(); it++) {
double r_prime = r;
double nu_prime = nu;
double s_prime = *it;
double mu_prime = mu;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logp += -log(s_prime);
logps.push_back(logp);
}
return logps;
}
vector<double> calc_continuous_mu_conditionals(std::vector<double> mu_grid,
int count,
double sum_x,
double sum_x_sq,
double r,
double nu,
double s) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=mu_grid.begin(); it!=mu_grid.end(); it++) {
double r_prime = r;
double nu_prime = nu;
double s_prime = s;
double mu_prime = *it;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logps.push_back(logp);
}
return logps;
}
double calc_multinomial_marginal_logp(int count,
const map<string, double> counts,
int K,
double dirichlet_alpha) {
double sum_lgammas = 0;
map<string, double>::const_iterator it;
for(it=counts.begin(); it!=counts.end(); it++) {
int label_count = it->second;
sum_lgammas += lgamma(label_count + dirichlet_alpha);
}
int missing_labels = K - counts.size();
if(missing_labels != 0) {
sum_lgammas += missing_labels * lgamma(dirichlet_alpha);
}
double marginal_logp = lgamma(K * dirichlet_alpha) \
- K * lgamma(dirichlet_alpha) \
+ sum_lgammas \
- lgamma(count + K * dirichlet_alpha);
return marginal_logp;
}
double calc_multinomial_predictive_logp(string element,
map<string, double> counts,
int sum_counts,
int K, double dirichlet_alpha) {
map<string, double>::iterator it = counts.find(element);
double numerator = dirichlet_alpha;
if(it!=counts.end()) {
numerator += counts[element];
}
double denominator = sum_counts + K * dirichlet_alpha;
return numerator / denominator;
}
vector<double> calc_multinomial_dirichlet_alpha_conditional(vector<double> dirichlet_alpha_grid,
int count,
map<string, double> counts,
int K) {
vector<double> logps;
vector<double>::iterator it;
for(it=dirichlet_alpha_grid.begin(); it!=dirichlet_alpha_grid.end(); it++) {
double dirichlet_alpha = *it;
double logp = calc_multinomial_marginal_logp(count, counts, K,
dirichlet_alpha);
logps.push_back(logp);
}
return logps;
}
} // namespace numerics
<commit_msg>move hyper prior into calc_continuous_log_Z<commit_after>#include "numerics.h"
using namespace std;
namespace numerics {
// subtract minimum value, logaddexp residuals, pass residuals and partition to
// draw_sample_with_partition
int draw_sample_unnormalized(vector<double> unorm_logps, double rand_u) {
double max_el = *std::max_element(unorm_logps.begin(), unorm_logps.end());
double partition = 0;
vector<double>::iterator it = unorm_logps.begin();
for(; it!=unorm_logps.end(); it++) {
*it -= max_el;
partition += exp(*it);
}
double log_partition = log(partition);
int draw = draw_sample_with_partition(unorm_logps, log_partition,
rand_u);
return draw;
}
int draw_sample_with_partition(vector<double> unorm_logps,
double log_partition, double rand_u) {
int draw = 0;
vector<double>::iterator it = unorm_logps.begin();
for(; it!=unorm_logps.end(); it++) {
rand_u -= exp(*it - log_partition);
if(rand_u < 0) {
return draw;
}
draw++;
}
// FIXME: should this fail?
assert(rand_u < 1E-10);
return draw;
}
// draw_sample_with_partition w/o exp() of ratio and no test for p(last)
// only useful for crp_init or supercluster swapping since no data component
int crp_draw_sample(vector<int> counts, int sum_counts, double alpha,
double rand_u) {
int draw = 0;
double partition = sum_counts + alpha;
vector<int>::iterator it = counts.begin();
for(; it!=counts.end(); it++) {
rand_u -= (*it / partition);
if(rand_u <0) {
return draw;
}
draw++;
}
// new cluster
return draw;
}
// p(alpha | clusters)
double calc_crp_alpha_conditional(std::vector<int> counts,
double alpha, int sum_counts,
bool absolute) {
int num_clusters = counts.size();
if(sum_counts==-1) {
sum_counts = std::accumulate(counts.begin(), counts.end(), 0);
}
double logp = lgamma(alpha) \
+ num_clusters * log(alpha) \
- lgamma(alpha + sum_counts);
// absolute necessary for determining true distribution rather than relative
if(absolute) {
double sum_log_gammas = 0;
std::vector<int>::iterator it = counts.begin();
for(; it!=counts.end(); it++) {
sum_log_gammas += lgamma(*it);
}
logp += sum_log_gammas;
}
return logp;
}
// helper for may calls to calc_crp_alpha_conditional
std::vector<double> calc_crp_alpha_conditionals(std::vector<double> grid,
std::vector<int> counts,
bool absolute) {
int sum_counts = std::accumulate(counts.begin(), counts.end(), 0);
std::vector<double> logps;
std::vector<double>::iterator it = grid.begin();
for(; it!=grid.end(); it++) {
double alpha = *it;
double logp = calc_crp_alpha_conditional(counts, alpha,
sum_counts, absolute);
logps.push_back(logp);
}
// note: prior distribution must still be added
return logps;
}
// p(z=cluster | alpha, clusters)
double calc_cluster_crp_logp(double cluster_weight, double sum_weights,
double alpha) {
if(cluster_weight == 0) {
cluster_weight = alpha;
}
double log_numerator = log(cluster_weight);
// presumes data has already been removed from the model
double log_denominator = log(sum_weights + alpha);
double log_probability = log_numerator - log_denominator;
return log_probability;
}
void insert_to_continuous_suffstats(int &count,
double &sum_x, double &sum_x_sq,
double el) {
count += 1;
sum_x += el;
sum_x_sq += el * el;
}
void remove_from_continuous_suffstats(int &count,
double &sum_x, double &sum_x_sq,
double el) {
count -= 1;
sum_x -= el;
sum_x_sq -= el * el;
}
/*
r' = r + n
nu' = nu + n
m' = m + (X-nm)/(r+n)
s' = s + C + rm**2 - r'm'**2
*/
void update_continuous_hypers(int count,
double sum_x, double sum_x_sq,
double &r, double &nu,
double &s, double &mu) {
double r_prime = r + count;
double nu_prime = nu + count;
double mu_prime = ((r * mu) + sum_x) / r_prime;
double s_prime = s + sum_x_sq \
+ (r * mu * mu) \
- (r_prime * mu_prime * mu_prime);
//
r = r_prime;
nu = nu_prime;
s = s_prime;
mu = mu_prime;
}
double calc_hyperprior(double r, double nu, double s) {
double logp = 0;
logp += -log(r);
logp += -log(nu);
logp += -log(s);
return logp;
}
double calc_continuous_log_Z(double r, double nu, double s) {
double nu_over_2 = .5 * nu;
double log_Z = nu_over_2 * (LOG_2 - log(s)) \
+ HALF_LOG_2PI \
- .5 * log(r) \
+ lgamma(nu_over_2);
log_Z += calc_hyperprior(r, nu, s);
return log_Z;
}
double calc_continuous_logp(int count,
double r, double nu,
double s,
double log_Z_0) {
return -count * HALF_LOG_2PI + calc_continuous_log_Z(r, nu, s) - log_Z_0;
}
double calc_continuous_data_logp(int count,
double sum_x, double sum_x_sq,
double r, double nu,
double s, double mu,
double el,
double score_0) {
insert_to_continuous_suffstats(count, sum_x, sum_x_sq, el);
update_continuous_hypers(count, sum_x, sum_x_sq, r, nu, s, mu);
double logp = calc_continuous_logp(count, r, nu, s, score_0);
return logp;
}
vector<double> calc_continuous_r_conditionals(std::vector<double> r_grid,
int count,
double sum_x,
double sum_x_sq,
double nu,
double s,
double mu) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=r_grid.begin(); it!=r_grid.end(); it++) {
double r_prime = *it;
double nu_prime = nu;
double s_prime = s;
double mu_prime = mu;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logps.push_back(logp);
}
return logps;
}
vector<double> calc_continuous_nu_conditionals(std::vector<double> nu_grid,
int count,
double sum_x,
double sum_x_sq,
double r,
double s,
double mu) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=nu_grid.begin(); it!=nu_grid.end(); it++) {
double r_prime = r;
double nu_prime = *it;
double s_prime = s;
double mu_prime = mu;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logps.push_back(logp);
}
return logps;
}
vector<double> calc_continuous_s_conditionals(std::vector<double> s_grid,
int count,
double sum_x,
double sum_x_sq,
double r,
double nu,
double mu) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=s_grid.begin(); it!=s_grid.end(); it++) {
double r_prime = r;
double nu_prime = nu;
double s_prime = *it;
double mu_prime = mu;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logps.push_back(logp);
}
return logps;
}
vector<double> calc_continuous_mu_conditionals(std::vector<double> mu_grid,
int count,
double sum_x,
double sum_x_sq,
double r,
double nu,
double s) {
std::vector<double> logps;
std::vector<double>::iterator it;
for(it=mu_grid.begin(); it!=mu_grid.end(); it++) {
double r_prime = r;
double nu_prime = nu;
double s_prime = s;
double mu_prime = *it;
double log_Z_0 = calc_continuous_log_Z(r_prime, nu_prime, s_prime);
update_continuous_hypers(count, sum_x, sum_x_sq,
r_prime, nu_prime, s_prime, mu_prime);
double logp = calc_continuous_logp(count,
r_prime, nu_prime, s_prime,
log_Z_0);
logps.push_back(logp);
}
return logps;
}
double calc_multinomial_marginal_logp(int count,
const map<string, double> counts,
int K,
double dirichlet_alpha) {
double sum_lgammas = 0;
map<string, double>::const_iterator it;
for(it=counts.begin(); it!=counts.end(); it++) {
int label_count = it->second;
sum_lgammas += lgamma(label_count + dirichlet_alpha);
}
int missing_labels = K - counts.size();
if(missing_labels != 0) {
sum_lgammas += missing_labels * lgamma(dirichlet_alpha);
}
double marginal_logp = lgamma(K * dirichlet_alpha) \
- K * lgamma(dirichlet_alpha) \
+ sum_lgammas \
- lgamma(count + K * dirichlet_alpha);
return marginal_logp;
}
double calc_multinomial_predictive_logp(string element,
map<string, double> counts,
int sum_counts,
int K, double dirichlet_alpha) {
map<string, double>::iterator it = counts.find(element);
double numerator = dirichlet_alpha;
if(it!=counts.end()) {
numerator += counts[element];
}
double denominator = sum_counts + K * dirichlet_alpha;
return numerator / denominator;
}
vector<double> calc_multinomial_dirichlet_alpha_conditional(vector<double> dirichlet_alpha_grid,
int count,
map<string, double> counts,
int K) {
vector<double> logps;
vector<double>::iterator it;
for(it=dirichlet_alpha_grid.begin(); it!=dirichlet_alpha_grid.end(); it++) {
double dirichlet_alpha = *it;
double logp = calc_multinomial_marginal_logp(count, counts, K,
dirichlet_alpha);
logps.push_back(logp);
}
return logps;
}
} // namespace numerics
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Win32NonBlockingDispatcher.h"
#include <cassert>
#include <mutex>
#include <optional>
#include <queue>
#if defined(_WIN32)
// WTL includes
#define NOMINMAX
#include <Windows.h>
#include <atlapp.h>
#include <atlbase.h>
namespace isc
{
struct Win32NonBlockingDispatcher::Impl
: public ATL::CWindowImpl<Impl>
{
using mutex_lock = std::lock_guard<std::mutex>;
enum
{
WM_DO_WORK = WM_USER + 1
};
Impl()
{
Create(HWND_MESSAGE);
}
~Impl()
{
DestroyWindow();
}
void Post(const Operation& operation)
{
{
mutex_lock lock(m_tasksMutex);
m_tasks.push(operation);
}
ATLVERIFY(PostMessage(WM_DO_WORK));
}
BEGIN_MSG_MAP(Impl)
MESSAGE_HANDLER(WM_DO_WORK, OnDoWork)
END_MSG_MAP()
private:
LRESULT OnDoWork(UINT /*nMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
DoWorkImpl();
return 0;
}
void DoWorkImpl()
{
// Reading count before execution protects us
// from "add-execute-add-execute-..." infinitive loop.
unsigned operationsCount = ReadOperationsCount();
while (operationsCount > 0)
{
--operationsCount;
Operation operation = PopOperation();
try
{
assert(operation);
operation();
}
catch (...)
{
}
}
}
size_t ReadOperationsCount()
{
// FIXME: we can avoid this extra lock.
mutex_lock lock(m_tasksMutex);
return m_tasks.size();
}
Operation PopOperation()
{
mutex_lock lock(m_tasksMutex);
assert(!m_tasks.empty());
Operation operation = m_tasks.front();
m_tasks.pop();
return operation;
}
std::queue<Operation> m_tasks;
std::mutex m_tasksMutex;
};
Win32NonBlockingDispatcher::Win32NonBlockingDispatcher()
: m_impl(std::make_unique<Impl>())
{
}
Win32NonBlockingDispatcher::~Win32NonBlockingDispatcher()
{
}
void Win32NonBlockingDispatcher::Dispatch(const Operation& operation)
{
m_impl->Post(operation);
}
}
#endif
<commit_msg>Исправил компиляцию под Windows, поломанную порядком include после форматирования<commit_after>#include "stdafx.h"
#include "Win32NonBlockingDispatcher.h"
#include <cassert>
#include <mutex>
#include <optional>
#include <queue>
#if defined(_WIN32)
// WTL includes
#define NOMINMAX
#include <Windows.h>
#include <atlbase.h>
#include <atlapp.h>
namespace isc
{
struct Win32NonBlockingDispatcher::Impl
: public ATL::CWindowImpl<Impl>
{
using mutex_lock = std::lock_guard<std::mutex>;
enum
{
WM_DO_WORK = WM_USER + 1
};
Impl()
{
Create(HWND_MESSAGE);
}
~Impl()
{
DestroyWindow();
}
void Post(const Operation& operation)
{
{
mutex_lock lock(m_tasksMutex);
m_tasks.push(operation);
}
ATLVERIFY(PostMessage(WM_DO_WORK));
}
BEGIN_MSG_MAP(Impl)
MESSAGE_HANDLER(WM_DO_WORK, OnDoWork)
END_MSG_MAP()
private:
LRESULT OnDoWork(UINT /*nMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
DoWorkImpl();
return 0;
}
void DoWorkImpl()
{
// Reading count before execution protects us
// from "add-execute-add-execute-..." infinitive loop.
unsigned operationsCount = ReadOperationsCount();
while (operationsCount > 0)
{
--operationsCount;
Operation operation = PopOperation();
try
{
assert(operation);
operation();
}
catch (...)
{
}
}
}
size_t ReadOperationsCount()
{
// FIXME: we can avoid this extra lock.
mutex_lock lock(m_tasksMutex);
return m_tasks.size();
}
Operation PopOperation()
{
mutex_lock lock(m_tasksMutex);
assert(!m_tasks.empty());
Operation operation = m_tasks.front();
m_tasks.pop();
return operation;
}
std::queue<Operation> m_tasks;
std::mutex m_tasksMutex;
};
Win32NonBlockingDispatcher::Win32NonBlockingDispatcher()
: m_impl(std::make_unique<Impl>())
{
}
Win32NonBlockingDispatcher::~Win32NonBlockingDispatcher()
{
}
void Win32NonBlockingDispatcher::Dispatch(const Operation& operation)
{
m_impl->Post(operation);
}
}
#endif
<|endoftext|>
|
<commit_before>// Only for Linux :)
#include <iostream>
// LEVEL TRIGGERED. Notification happens when we have something to read.
// 10 bytes received. System notifies us. We read 5. System notifies us again to read
// another 5.
// EDGE TRIGGERED. Notification happens when we have something to read.
// 10 bytes received. System notifies us. We read 5. System DOES NOT notify us again to read another 5. When next 10 will come, will be notified.
int main() {
return 0;
}
<commit_msg>epoll skeleton, not working yet<commit_after>// Only for Linux :)
// So we'll use Docker to compile this on OS X.
#include <iostream>
#include <algorithm>
#include <set>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
#define MAX_EVENTS 32
int set_nonblock(int fd) {
int flags;
if (-1 == (flags = fcntl(fd, F_GETFL, 0))) {
flags = 0;
}
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
// LEVEL TRIGGERED. Notification happens when we have something to read.
// 10 bytes received. System notifies us. We read 5. System notifies us again to read
// another 5.
// EDGE TRIGGERED. Notification happens when we have something to read.
// 10 bytes received. System notifies us. We read 5. System DOES NOT notify us again to read another 5. When next 10 will come, will be notified.
int main() {
int MasterSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in SockAddr;
SockAddr.sin_family = AF_INET;
SockAddr.sin_port = htons(12345);
SockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(MasterSocket, (struct sockaddr *)(&SockAddr), sizeof(SockAddr));
set_nonblock(MasterSocket);
listen(MasterSocket, SOMAXCONN);
while(true) {
for() {
}
}
return 0;
}
<|endoftext|>
|
<commit_before>//
// Utility class to do jet-by-jet correction
// Based on templates of ptJet vs ptTrack vs r
//
// Author: M.Verweij
#include "TH2.h"
#include "TH3.h"
#include "TProfile.h"
#include "TMath.h"
#include "TRandom3.h"
#include "TLorentzVector.h"
#include "AliEmcalJet.h"
#include "AliVParticle.h"
#include <TF1.h>
#include <TList.h>
#include <THnSparse.h>
#include "AliEmcalJetByJetCorrection.h"
ClassImp(AliEmcalJetByJetCorrection)
//__________________________________________________________________________
AliEmcalJetByJetCorrection::AliEmcalJetByJetCorrection() :
TNamed(),
fh3JetPtDRTrackPt(0x0),
fBinWidthJetPt(10.),
fJetPtMin(0.),
fJetPtMax(150.),
fCollTemplates(),
fInitialized(kFALSE),
fEfficiencyFixed(1.),
fhEfficiency(0),
fhSmoothEfficiency(0),
fCorrectpTtrack(0),
fNpPoisson(0),
fExternalNmissed(0),
fRndm(0),
fNMissedTracks(-1),
fpAppliedEfficiency(0),
fhNmissing(0),
fListOfOutput(0)
{
// Dummy constructor.
fCollTemplates.SetOwner(kTRUE);
}
//__________________________________________________________________________
AliEmcalJetByJetCorrection::AliEmcalJetByJetCorrection(const char* name) :
TNamed(name, name),
fh3JetPtDRTrackPt(0x0),
fBinWidthJetPt(10.),
fJetPtMin(0.),
fJetPtMax(150.),
fCollTemplates(),
fInitialized(kFALSE),
fEfficiencyFixed(1.),
fhEfficiency(0),
fhSmoothEfficiency(0),
fCorrectpTtrack(0),
fNpPoisson(0),
fExternalNmissed(0),
fRndm(0),
fNMissedTracks(-1),
fpAppliedEfficiency(0),
fhNmissing(0),
fListOfOutput(0)
{
// Default constructor.
fCollTemplates.SetOwner(kTRUE);
const Int_t nBinPt = 118; //0-2: 20 bins; 2-100: 98 bins
Double_t binLimitsPt[nBinPt+1];
for(Int_t iPt = 0;iPt <= nBinPt;iPt++){
if(iPt<20){
binLimitsPt[iPt] = 0. + (Double_t)iPt*0.15;
} else {// 1.0
binLimitsPt[iPt] = binLimitsPt[iPt-1] + 1.0;
}
}
const Int_t nBinsPtJ = 200;
const Double_t minPtJ = -50.;
const Double_t maxPtJ = 150.;
fpAppliedEfficiency = new TProfile("fpAppliedEfficiency","fpAppliedEfficiency",nBinPt,binLimitsPt);
const Int_t nvars = 5;
Int_t nbins[nvars] = {nBinsPtJ, 21 , 21 , 21 , 21};
Double_t minbin[nvars] = {minPtJ , 0. , 0. , 0. , 0.};
Double_t maxbin[nvars] = {maxPtJ , 20., 20., 20., 20.};
TString title = "fhNmissing", nameh = title;
TString axtitles[nvars] = {"#it{p}_{T,jet}", "N constituents added", "N_{constituents} #times (1/eff - 1)", "N_{truth}"};
for(Int_t i = 0; i<nvars; i++){
title+=axtitles[i];
}
fhNmissing = new THnSparseF(nameh.Data(), title.Data(), nvars, nbins, minbin, maxbin);
fListOfOutput = new TList();
fListOfOutput->SetName("JetByJetCorrectionOutput");
fListOfOutput->SetOwner();
fListOfOutput->Add(fpAppliedEfficiency);
fListOfOutput->Add(fhNmissing);
}
//__________________________________________________________________________
AliEmcalJetByJetCorrection::AliEmcalJetByJetCorrection(const AliEmcalJetByJetCorrection &other) :
TNamed(other),
fh3JetPtDRTrackPt(other.fh3JetPtDRTrackPt),
fBinWidthJetPt(other.fBinWidthJetPt),
fJetPtMin(other.fJetPtMin),
fJetPtMax(other.fJetPtMax),
fCollTemplates(other.fCollTemplates),
fInitialized(other.fInitialized),
fEfficiencyFixed(other.fEfficiencyFixed),
fhEfficiency(other.fhEfficiency),
fhSmoothEfficiency(other.fhSmoothEfficiency),
fCorrectpTtrack(other.fCorrectpTtrack),
fpAppliedEfficiency(other.fpAppliedEfficiency),
fRndm(other.fRndm)
fhNmissing(other.fhNmissing),
{
// Copy constructor.
}
//__________________________________________________________________________
AliEmcalJetByJetCorrection& AliEmcalJetByJetCorrection::operator=(const AliEmcalJetByJetCorrection &other)
{
// Assignment
if (&other == this) return *this;
TNamed::operator=(other);
fh3JetPtDRTrackPt = other.fh3JetPtDRTrackPt;
fBinWidthJetPt = other.fBinWidthJetPt;
fJetPtMin = other.fJetPtMin;
fJetPtMax = other.fJetPtMax;
fCollTemplates = other.fCollTemplates;
fInitialized = other.fInitialized;
fEfficiencyFixed = other.fEfficiencyFixed;
fhEfficiency = other.fhEfficiency;
fhSmoothEfficiency = other.fhSmoothEfficiency;
fCorrectpTtrack = other.fCorrectpTtrack;
fpAppliedEfficiency= other.fpAppliedEfficiency;
fhNmissing = other.fhNmissing;
fRndm = other.fRndm;
return *this;
}
//__________________________________________________________________________
AliEmcalJet* AliEmcalJetByJetCorrection::Eval(const AliEmcalJet *jet, TClonesArray *fTracks) {
if(!fInitialized) {
Printf("AliEmcalJetByJetCorrection %s not initialized",GetName());
return NULL;
}
Int_t bin = GetJetPtBin(jet->Pt());
if(bin<0 || bin>fCollTemplates.GetEntriesFast()) return NULL;
TH2D *hTemplate = static_cast<TH2D*>(fCollTemplates.At(bin));
Double_t meanPt = GetMeanPtConstituents(jet,fTracks);
Double_t eff = GetEfficiency(meanPt);
fpAppliedEfficiency->Fill(meanPt,eff);
Double_t fillarray[5]; //"#it{p}_{T,jet}", "N constituents added", "N_{constituents} #times (1/eff - 1)", "N_{truth}"
fillarray[0] = jet->Pt();
//np is the estimation of missed tracks
Int_t np = TMath::FloorNint((double)jet->GetNumberOfTracks() * (1./eff -1.));
fillarray[2] = np;
if(fExternalNmissed) {
np = fNMissedTracks; //if the number of missed tracks was calculated from external sources
fillarray[3] = fNMissedTracks;
}
//npc is the number of added tracks
Int_t npc=np; //take the particle missed as particle added
if(fNpPoisson){
npc=fRndm->Poisson(np); // smear the particle missed with a poissonian to get the number of added
}
fillarray[1] = npc;
fhNmissing->Fill(fillarray);
TLorentzVector corrVec; corrVec.SetPtEtaPhiM(jet->Pt(),jet->Eta(),jet->Phi(),jet->M());
Double_t mass = 0.13957; //pion mass
fArrayTrackCorr->Clear();
for(Int_t i = 0; i<npc; i++) {
Double_t r;
Double_t pt;
hTemplate->GetRandom2(r,pt);
Double_t t = TMath::TwoPi()*gRandom->Uniform(1.);
Double_t deta = r*TMath::Cos(t);
Double_t dphi = r*TMath::Sin(t);
TLorentzVector curVec;
curVec.SetPtEtaPhiM(pt,deta+jet->Eta(),dphi+jet->Phi(),mass);
new ((*fArrayTrackCorr)[i]) TLorentzVector(curVec);
corrVec+=curVec;
}
AliEmcalJet *jetCorr = new AliEmcalJet(corrVec.Pt(),corrVec.Eta(),corrVec.Phi(),corrVec.M());
Printf("ERROR: Need to implemet a fix here to set the jet acceptance correctly -> not done in the constructor AliEmcalJet(pt,eta,phi,m) just used. See JIRA https://alice.its.cern.ch/jira/browse/ALPHY-65. Use something like jet->SetJetAcceptanceType(fJetTask->FindJetAcceptanceType(eta,phi,r))");
return jetCorr;
}
//__________________________________________________________________________
void AliEmcalJetByJetCorrection::Init() {
//Init templates
if(!fh3JetPtDRTrackPt) {
Printf("%s fh3JetPtDRTrackPt not known",GetName());
fInitialized = kFALSE;
return;
}
if(!fhEfficiency && fEfficiencyFixed==1){
Printf("%s fhEfficiency not known",GetName());
fInitialized = kFALSE;
return;
}
fRndm = new TRandom3(1234);
if(fhEfficiency){
fhSmoothEfficiency = (TH1D*) fh3JetPtDRTrackPt->ProjectionZ("fhSmoothEfficiency"); //copy the binning of the pTtrack axis
Int_t nBinsEf = fhEfficiency->GetXaxis()->GetNbins();
Int_t nBinsEfSmth = fhSmoothEfficiency->GetXaxis()->GetNbins();
Double_t smallBinW = 0.9;
Double_t pTFitRange[2]={6,100}; //reset in the loop, silent warning
for(Int_t ibeff=0;ibeff<nBinsEf;ibeff++){
Double_t bw = fhEfficiency->GetBinWidth(ibeff+1);
if(bw>smallBinW){
pTFitRange[0] = fhEfficiency->GetBinLowEdge(ibeff);
break;
}
}
pTFitRange[1] = fhEfficiency->GetBinLowEdge(nBinsEf+1);
TF1* fitfuncEff = new TF1("fitfuncEff", "[0]+x*[1]", pTFitRange[0], pTFitRange[1]);
//fit function in the high pT region to smooth out fluctuations
fhEfficiency->Fit("fitfuncEff", "R0");
for(Int_t i=0;i<nBinsEfSmth;i++){
Double_t binCentreT=fhSmoothEfficiency->GetBinCenter(i+1);
Int_t bin = fhEfficiency->FindBin(binCentreT);
//Double_t binEff = fhEfficiency->GetBinContent(bin);
//fill histogram fhSmoothEfficiency by interpolation or function
if(fhEfficiency->GetBinWidth(bin) > smallBinW){
fhSmoothEfficiency->SetBinContent(i+1,fitfuncEff->Eval(binCentreT));
} else {
Double_t effInterp = fhEfficiency->Interpolate(binCentreT);
fhSmoothEfficiency ->SetBinContent(i+1,effInterp);
fhSmoothEfficiency ->SetBinError(i+1,0.);
}
}
}
if(fJetPtMax>fh3JetPtDRTrackPt->GetXaxis()->GetXmax())
fJetPtMax = fh3JetPtDRTrackPt->GetXaxis()->GetXmax();
if(fJetPtMin<fh3JetPtDRTrackPt->GetXaxis()->GetXmin())
fJetPtMin = fh3JetPtDRTrackPt->GetXaxis()->GetXmin();
Double_t eps = 0.00001;
Int_t counter = 0;
for(Double_t ptmin = fJetPtMin; ptmin<fJetPtMax; ptmin+=fBinWidthJetPt) {
Int_t binMin = fh3JetPtDRTrackPt->GetXaxis()->FindBin(ptmin+eps);
Int_t binMax = fh3JetPtDRTrackPt->GetXaxis()->FindBin(ptmin+fBinWidthJetPt-eps);
fh3JetPtDRTrackPt->GetXaxis()->SetRange(binMin,binMax);
Int_t nBinspTtr = fh3JetPtDRTrackPt->GetZaxis()->GetNbins();
Int_t nBinsr = fh3JetPtDRTrackPt->GetYaxis()->GetNbins();
TH2D *h2 = dynamic_cast<TH2D*>(fh3JetPtDRTrackPt->Project3D("zy"));
if(h2){
h2->SetName(Form("hPtR_%.0f_%.0f",fh3JetPtDRTrackPt->GetXaxis()->GetBinLowEdge(binMin),fh3JetPtDRTrackPt->GetXaxis()->GetBinUpEdge(binMax)));
if(fCorrectpTtrack) {
//apply efficiency correction to pTtrack
for(Int_t ipTtr=0;ipTtr<nBinspTtr;ipTtr++){
for(Int_t ir=0;ir<nBinsr;ir++){
Double_t uncorr = h2->GetBinContent(ir+1,ipTtr+1);
Double_t corr = uncorr/GetEfficiency(h2->GetYaxis()->GetBinCenter(ipTtr+1));
h2->SetBinContent(ir+1, ipTtr+1, corr);
}
}
}
}
fCollTemplates.Add(h2);
fListOfOutput->Add(h2);
counter++;
}
// Int_t nt = TMath::FloorNint((fJetPtMax-fJetPtMin)/fBinWidthJetPt);
// Printf("nt: %d entries fCollTemplates: %d",nt,fCollTemplates.GetEntriesFast());
fArrayTrackCorr = new TClonesArray("TLorentzVector", 20);
fInitialized = kTRUE;
}
//__________________________________________________________________________
Int_t AliEmcalJetByJetCorrection::GetJetPtBin(const Double_t jetpt) const {
if(jetpt<fJetPtMin || jetpt>=fJetPtMax)
return -1;
Int_t bin = TMath::FloorNint((jetpt - fJetPtMin)/fBinWidthJetPt);
return bin;
}
//________________________________________________________________________
Double_t AliEmcalJetByJetCorrection::GetEfficiency(const Double_t pt) const {
Double_t eff = 1.;
if(fEfficiencyFixed<1.) return fEfficiencyFixed;
else if(fhSmoothEfficiency) {
Int_t bin = fhSmoothEfficiency->GetXaxis()->FindBin(pt);
eff = fhSmoothEfficiency->GetBinContent(bin);
//Printf("Efficiency (pT = %.2f, bin %d) = %.2f", pt, bin, eff);
}
return eff;
}
//________________________________________________________________________
Double_t AliEmcalJetByJetCorrection::GetMeanPtConstituents(const AliEmcalJet *jet, TClonesArray *fTracks) const {
if(!jet || !fTracks) return -1.;
if(jet->GetNumberOfTracks()<1) return -1;
AliVParticle *vp;
Double_t sumPtCh = 0.;
for(Int_t icc=0; icc<jet->GetNumberOfTracks(); icc++) {
vp = static_cast<AliVParticle*>(jet->TrackAt(icc, fTracks));
if(!vp) continue;
sumPtCh+=vp->Pt();
}
Double_t meanpt = sumPtCh/(double)(jet->GetNumberOfTracks());
return meanpt;
}
<commit_msg>AliEmcalJetByJetCorrection fix comma typo of previous commit<commit_after>//
// Utility class to do jet-by-jet correction
// Based on templates of ptJet vs ptTrack vs r
//
// Author: M.Verweij
#include "TH2.h"
#include "TH3.h"
#include "TProfile.h"
#include "TMath.h"
#include "TRandom3.h"
#include "TLorentzVector.h"
#include "AliEmcalJet.h"
#include "AliVParticle.h"
#include <TF1.h>
#include <TList.h>
#include <THnSparse.h>
#include "AliEmcalJetByJetCorrection.h"
ClassImp(AliEmcalJetByJetCorrection)
//__________________________________________________________________________
AliEmcalJetByJetCorrection::AliEmcalJetByJetCorrection() :
TNamed(),
fh3JetPtDRTrackPt(0x0),
fBinWidthJetPt(10.),
fJetPtMin(0.),
fJetPtMax(150.),
fCollTemplates(),
fInitialized(kFALSE),
fEfficiencyFixed(1.),
fhEfficiency(0),
fhSmoothEfficiency(0),
fCorrectpTtrack(0),
fNpPoisson(0),
fExternalNmissed(0),
fRndm(0),
fNMissedTracks(-1),
fpAppliedEfficiency(0),
fhNmissing(0),
fListOfOutput(0)
{
// Dummy constructor.
fCollTemplates.SetOwner(kTRUE);
}
//__________________________________________________________________________
AliEmcalJetByJetCorrection::AliEmcalJetByJetCorrection(const char* name) :
TNamed(name, name),
fh3JetPtDRTrackPt(0x0),
fBinWidthJetPt(10.),
fJetPtMin(0.),
fJetPtMax(150.),
fCollTemplates(),
fInitialized(kFALSE),
fEfficiencyFixed(1.),
fhEfficiency(0),
fhSmoothEfficiency(0),
fCorrectpTtrack(0),
fNpPoisson(0),
fExternalNmissed(0),
fRndm(0),
fNMissedTracks(-1),
fpAppliedEfficiency(0),
fhNmissing(0),
fListOfOutput(0)
{
// Default constructor.
fCollTemplates.SetOwner(kTRUE);
const Int_t nBinPt = 118; //0-2: 20 bins; 2-100: 98 bins
Double_t binLimitsPt[nBinPt+1];
for(Int_t iPt = 0;iPt <= nBinPt;iPt++){
if(iPt<20){
binLimitsPt[iPt] = 0. + (Double_t)iPt*0.15;
} else {// 1.0
binLimitsPt[iPt] = binLimitsPt[iPt-1] + 1.0;
}
}
const Int_t nBinsPtJ = 200;
const Double_t minPtJ = -50.;
const Double_t maxPtJ = 150.;
fpAppliedEfficiency = new TProfile("fpAppliedEfficiency","fpAppliedEfficiency",nBinPt,binLimitsPt);
const Int_t nvars = 5;
Int_t nbins[nvars] = {nBinsPtJ, 21 , 21 , 21 , 21};
Double_t minbin[nvars] = {minPtJ , 0. , 0. , 0. , 0.};
Double_t maxbin[nvars] = {maxPtJ , 20., 20., 20., 20.};
TString title = "fhNmissing", nameh = title;
TString axtitles[nvars] = {"#it{p}_{T,jet}", "N constituents added", "N_{constituents} #times (1/eff - 1)", "N_{truth}"};
for(Int_t i = 0; i<nvars; i++){
title+=axtitles[i];
}
fhNmissing = new THnSparseF(nameh.Data(), title.Data(), nvars, nbins, minbin, maxbin);
fListOfOutput = new TList();
fListOfOutput->SetName("JetByJetCorrectionOutput");
fListOfOutput->SetOwner();
fListOfOutput->Add(fpAppliedEfficiency);
fListOfOutput->Add(fhNmissing);
}
//__________________________________________________________________________
AliEmcalJetByJetCorrection::AliEmcalJetByJetCorrection(const AliEmcalJetByJetCorrection &other) :
TNamed(other),
fh3JetPtDRTrackPt(other.fh3JetPtDRTrackPt),
fBinWidthJetPt(other.fBinWidthJetPt),
fJetPtMin(other.fJetPtMin),
fJetPtMax(other.fJetPtMax),
fCollTemplates(other.fCollTemplates),
fInitialized(other.fInitialized),
fEfficiencyFixed(other.fEfficiencyFixed),
fhEfficiency(other.fhEfficiency),
fhSmoothEfficiency(other.fhSmoothEfficiency),
fCorrectpTtrack(other.fCorrectpTtrack),
fpAppliedEfficiency(other.fpAppliedEfficiency),
fRndm(other.fRndm),
fhNmissing(other.fhNmissing)
{
// Copy constructor.
}
//__________________________________________________________________________
AliEmcalJetByJetCorrection& AliEmcalJetByJetCorrection::operator=(const AliEmcalJetByJetCorrection &other)
{
// Assignment
if (&other == this) return *this;
TNamed::operator=(other);
fh3JetPtDRTrackPt = other.fh3JetPtDRTrackPt;
fBinWidthJetPt = other.fBinWidthJetPt;
fJetPtMin = other.fJetPtMin;
fJetPtMax = other.fJetPtMax;
fCollTemplates = other.fCollTemplates;
fInitialized = other.fInitialized;
fEfficiencyFixed = other.fEfficiencyFixed;
fhEfficiency = other.fhEfficiency;
fhSmoothEfficiency = other.fhSmoothEfficiency;
fCorrectpTtrack = other.fCorrectpTtrack;
fpAppliedEfficiency= other.fpAppliedEfficiency;
fhNmissing = other.fhNmissing;
fRndm = other.fRndm;
return *this;
}
//__________________________________________________________________________
AliEmcalJet* AliEmcalJetByJetCorrection::Eval(const AliEmcalJet *jet, TClonesArray *fTracks) {
if(!fInitialized) {
Printf("AliEmcalJetByJetCorrection %s not initialized",GetName());
return NULL;
}
Int_t bin = GetJetPtBin(jet->Pt());
if(bin<0 || bin>fCollTemplates.GetEntriesFast()) return NULL;
TH2D *hTemplate = static_cast<TH2D*>(fCollTemplates.At(bin));
Double_t meanPt = GetMeanPtConstituents(jet,fTracks);
Double_t eff = GetEfficiency(meanPt);
fpAppliedEfficiency->Fill(meanPt,eff);
Double_t fillarray[5]; //"#it{p}_{T,jet}", "N constituents added", "N_{constituents} #times (1/eff - 1)", "N_{truth}"
fillarray[0] = jet->Pt();
//np is the estimation of missed tracks
Int_t np = TMath::FloorNint((double)jet->GetNumberOfTracks() * (1./eff -1.));
fillarray[2] = np;
if(fExternalNmissed) {
np = fNMissedTracks; //if the number of missed tracks was calculated from external sources
fillarray[3] = fNMissedTracks;
}
//npc is the number of added tracks
Int_t npc=np; //take the particle missed as particle added
if(fNpPoisson){
npc=fRndm->Poisson(np); // smear the particle missed with a poissonian to get the number of added
}
fillarray[1] = npc;
fhNmissing->Fill(fillarray);
TLorentzVector corrVec; corrVec.SetPtEtaPhiM(jet->Pt(),jet->Eta(),jet->Phi(),jet->M());
Double_t mass = 0.13957; //pion mass
fArrayTrackCorr->Clear();
for(Int_t i = 0; i<npc; i++) {
Double_t r;
Double_t pt;
hTemplate->GetRandom2(r,pt);
Double_t t = TMath::TwoPi()*gRandom->Uniform(1.);
Double_t deta = r*TMath::Cos(t);
Double_t dphi = r*TMath::Sin(t);
TLorentzVector curVec;
curVec.SetPtEtaPhiM(pt,deta+jet->Eta(),dphi+jet->Phi(),mass);
new ((*fArrayTrackCorr)[i]) TLorentzVector(curVec);
corrVec+=curVec;
}
AliEmcalJet *jetCorr = new AliEmcalJet(corrVec.Pt(),corrVec.Eta(),corrVec.Phi(),corrVec.M());
Printf("ERROR: Need to implemet a fix here to set the jet acceptance correctly -> not done in the constructor AliEmcalJet(pt,eta,phi,m) just used. See JIRA https://alice.its.cern.ch/jira/browse/ALPHY-65. Use something like jet->SetJetAcceptanceType(fJetTask->FindJetAcceptanceType(eta,phi,r))");
return jetCorr;
}
//__________________________________________________________________________
void AliEmcalJetByJetCorrection::Init() {
//Init templates
if(!fh3JetPtDRTrackPt) {
Printf("%s fh3JetPtDRTrackPt not known",GetName());
fInitialized = kFALSE;
return;
}
if(!fhEfficiency && fEfficiencyFixed==1){
Printf("%s fhEfficiency not known",GetName());
fInitialized = kFALSE;
return;
}
fRndm = new TRandom3(1234);
if(fhEfficiency){
fhSmoothEfficiency = (TH1D*) fh3JetPtDRTrackPt->ProjectionZ("fhSmoothEfficiency"); //copy the binning of the pTtrack axis
Int_t nBinsEf = fhEfficiency->GetXaxis()->GetNbins();
Int_t nBinsEfSmth = fhSmoothEfficiency->GetXaxis()->GetNbins();
Double_t smallBinW = 0.9;
Double_t pTFitRange[2]={6,100}; //reset in the loop, silent warning
for(Int_t ibeff=0;ibeff<nBinsEf;ibeff++){
Double_t bw = fhEfficiency->GetBinWidth(ibeff+1);
if(bw>smallBinW){
pTFitRange[0] = fhEfficiency->GetBinLowEdge(ibeff);
break;
}
}
pTFitRange[1] = fhEfficiency->GetBinLowEdge(nBinsEf+1);
TF1* fitfuncEff = new TF1("fitfuncEff", "[0]+x*[1]", pTFitRange[0], pTFitRange[1]);
//fit function in the high pT region to smooth out fluctuations
fhEfficiency->Fit("fitfuncEff", "R0");
for(Int_t i=0;i<nBinsEfSmth;i++){
Double_t binCentreT=fhSmoothEfficiency->GetBinCenter(i+1);
Int_t bin = fhEfficiency->FindBin(binCentreT);
//Double_t binEff = fhEfficiency->GetBinContent(bin);
//fill histogram fhSmoothEfficiency by interpolation or function
if(fhEfficiency->GetBinWidth(bin) > smallBinW){
fhSmoothEfficiency->SetBinContent(i+1,fitfuncEff->Eval(binCentreT));
} else {
Double_t effInterp = fhEfficiency->Interpolate(binCentreT);
fhSmoothEfficiency ->SetBinContent(i+1,effInterp);
fhSmoothEfficiency ->SetBinError(i+1,0.);
}
}
}
if(fJetPtMax>fh3JetPtDRTrackPt->GetXaxis()->GetXmax())
fJetPtMax = fh3JetPtDRTrackPt->GetXaxis()->GetXmax();
if(fJetPtMin<fh3JetPtDRTrackPt->GetXaxis()->GetXmin())
fJetPtMin = fh3JetPtDRTrackPt->GetXaxis()->GetXmin();
Double_t eps = 0.00001;
Int_t counter = 0;
for(Double_t ptmin = fJetPtMin; ptmin<fJetPtMax; ptmin+=fBinWidthJetPt) {
Int_t binMin = fh3JetPtDRTrackPt->GetXaxis()->FindBin(ptmin+eps);
Int_t binMax = fh3JetPtDRTrackPt->GetXaxis()->FindBin(ptmin+fBinWidthJetPt-eps);
fh3JetPtDRTrackPt->GetXaxis()->SetRange(binMin,binMax);
Int_t nBinspTtr = fh3JetPtDRTrackPt->GetZaxis()->GetNbins();
Int_t nBinsr = fh3JetPtDRTrackPt->GetYaxis()->GetNbins();
TH2D *h2 = dynamic_cast<TH2D*>(fh3JetPtDRTrackPt->Project3D("zy"));
if(h2){
h2->SetName(Form("hPtR_%.0f_%.0f",fh3JetPtDRTrackPt->GetXaxis()->GetBinLowEdge(binMin),fh3JetPtDRTrackPt->GetXaxis()->GetBinUpEdge(binMax)));
if(fCorrectpTtrack) {
//apply efficiency correction to pTtrack
for(Int_t ipTtr=0;ipTtr<nBinspTtr;ipTtr++){
for(Int_t ir=0;ir<nBinsr;ir++){
Double_t uncorr = h2->GetBinContent(ir+1,ipTtr+1);
Double_t corr = uncorr/GetEfficiency(h2->GetYaxis()->GetBinCenter(ipTtr+1));
h2->SetBinContent(ir+1, ipTtr+1, corr);
}
}
}
}
fCollTemplates.Add(h2);
fListOfOutput->Add(h2);
counter++;
}
// Int_t nt = TMath::FloorNint((fJetPtMax-fJetPtMin)/fBinWidthJetPt);
// Printf("nt: %d entries fCollTemplates: %d",nt,fCollTemplates.GetEntriesFast());
fArrayTrackCorr = new TClonesArray("TLorentzVector", 20);
fInitialized = kTRUE;
}
//__________________________________________________________________________
Int_t AliEmcalJetByJetCorrection::GetJetPtBin(const Double_t jetpt) const {
if(jetpt<fJetPtMin || jetpt>=fJetPtMax)
return -1;
Int_t bin = TMath::FloorNint((jetpt - fJetPtMin)/fBinWidthJetPt);
return bin;
}
//________________________________________________________________________
Double_t AliEmcalJetByJetCorrection::GetEfficiency(const Double_t pt) const {
Double_t eff = 1.;
if(fEfficiencyFixed<1.) return fEfficiencyFixed;
else if(fhSmoothEfficiency) {
Int_t bin = fhSmoothEfficiency->GetXaxis()->FindBin(pt);
eff = fhSmoothEfficiency->GetBinContent(bin);
//Printf("Efficiency (pT = %.2f, bin %d) = %.2f", pt, bin, eff);
}
return eff;
}
//________________________________________________________________________
Double_t AliEmcalJetByJetCorrection::GetMeanPtConstituents(const AliEmcalJet *jet, TClonesArray *fTracks) const {
if(!jet || !fTracks) return -1.;
if(jet->GetNumberOfTracks()<1) return -1;
AliVParticle *vp;
Double_t sumPtCh = 0.;
for(Int_t icc=0; icc<jet->GetNumberOfTracks(); icc++) {
vp = static_cast<AliVParticle*>(jet->TrackAt(icc, fTracks));
if(!vp) continue;
sumPtCh+=vp->Pt();
}
Double_t meanpt = sumPtCh/(double)(jet->GetNumberOfTracks());
return meanpt;
}
<|endoftext|>
|
<commit_before>// FXStudioCore.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "FXStudioCore.h"
#include "FXStudioApp.h"
#include "FXStudioView.h"
FXSTUDIOCORE_API int CreateInstance(
int *instancePtrAddress,
int *hPrevInstancePtrAddress,
int *hWndPtrAddress,
int nCmdShow,
int screenWidth, int screenHeight)
{
HINSTANCE hInstance = (HINSTANCE)instancePtrAddress;
HINSTANCE hPrevInstance = (HINSTANCE)hPrevInstancePtrAddress;
HWND hWnd = (HWND)hWndPtrAddress;
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF;
_CrtSetDbgFlag(tmpDbgFlag);
SetCurrentDirectory(Utility::GetExecutableDirectory().c_str());
Logger::Init("logging.xml");
if (g_pApp != nullptr)
{
g_pApp->GetGameConfig().InitConfig("EditorOptions.xml", nullptr);
if (g_pApp->InitEnvironment())
{
g_pApp->GetGameConfig().m_ScreenWidth = screenWidth;
g_pApp->GetGameConfig().m_ScreenWidth = screenHeight;
g_pApp->SetupWindow(hInstance, hWnd);
if (g_pApp->InitRenderer())
{
g_pApp->OnStartRender();
}
}
}
return true;
}
FXSTUDIOCORE_API int DestroyInstance()
{
g_pApp->OnClose();
Logger::Destroy();
return 0;
}
FXSTUDIOCORE_API void ResizeWnd(int screenWidth, int screenHeight)
{
g_pApp->OnResize(screenWidth, screenHeight);
}
FXSTUDIOCORE_API void WndProc(int *hWndPtrAddress, int uMsg, int* wParam, int* lParam)
{
HWND hWnd = (HWND)hWndPtrAddress;
switch (uMsg)
{
case WM_CLOSE:
g_pApp->OnClose();
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_CHAR:
case WM_MOUSEMOVE:
case WM_MOUSEWHEEL:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
{
if (g_pApp->GetGameLogic() != nullptr)
{
AppMsg msg;
msg.m_hWnd = hWnd;
msg.m_uMsg = uMsg;
msg.m_wParam = WPARAM(wParam);
msg.m_lParam = LPARAM(lParam);
g_pApp->OnDispatchMsg(msg);
}
break;
}
}
}
FXSTUDIOCORE_API void RenderFrame()
{
g_pApp->OnRenderFrame();
}
FXSTUDIOCORE_API bool IsGameRunning()
{
return true;
}
FXSTUDIOCORE_API void OpenProject(BSTR lFileName)
{
std::string project = Utility::WS2S(std::wstring(lFileName, SysStringLen(lFileName)));
FXStudioLogic* pEditorLogic = dynamic_cast<FXStudioLogic*>(g_pApp->GetGameLogic());
if (pEditorLogic != nullptr)
{
g_pApp->GetGameConfig().m_Project = project;
pEditorLogic->VChangeState(BGS_LoadingGameEnvironment);
}
}
FXSTUDIOCORE_API void CreateNewProject(BSTR lFileName)
{
std::string project = Utility::WS2S(std::wstring(lFileName, SysStringLen(lFileName)));
FXStudioLogic* pEditorLogic = dynamic_cast<FXStudioLogic*>(g_pApp->GetGameLogic());
if (pEditorLogic != nullptr)
{
pEditorLogic->VCreateNewProject(project);
}
}
FXSTUDIOCORE_API unsigned int AddActor(BSTR actorResource)
{
std::string actorXml = Utility::WS2S(std::wstring(actorResource, SysStringLen(actorResource)));
StrongActorPtr pActor = g_pApp->GetGameLogic()->VCreateActor(actorXml);
if (!pActor)
return INVALID_ACTOR_ID;
return pActor->GetActorId();
}
FXSTUDIOCORE_API bool ModifyActor(BSTR modificationXml)
{
return true;
}
FXSTUDIOCORE_API bool RemoveActor(unsigned int actorId)
{
g_pApp->GetGameLogic()->VDestroyActor(actorId);
return true;
}
<commit_msg>to do<commit_after>// FXStudioCore.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "FXStudioCore.h"
#include "FXStudioApp.h"
#include "FXStudioView.h"
FXSTUDIOCORE_API int CreateInstance(
int *instancePtrAddress,
int *hPrevInstancePtrAddress,
int *hWndPtrAddress,
int nCmdShow,
int screenWidth, int screenHeight)
{
HINSTANCE hInstance = (HINSTANCE)instancePtrAddress;
HINSTANCE hPrevInstance = (HINSTANCE)hPrevInstancePtrAddress;
HWND hWnd = (HWND)hWndPtrAddress;
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF;
_CrtSetDbgFlag(tmpDbgFlag);
SetCurrentDirectory(Utility::GetExecutableDirectory().c_str());
Logger::Init("logging.xml");
if (g_pApp != nullptr)
{
g_pApp->GetGameConfig().InitConfig("EditorOptions.xml", nullptr);
if (g_pApp->InitEnvironment())
{
g_pApp->GetGameConfig().m_ScreenWidth = screenWidth;
g_pApp->GetGameConfig().m_ScreenWidth = screenHeight;
g_pApp->SetupWindow(hInstance, hWnd);
if (g_pApp->InitRenderer())
{
g_pApp->OnStartRender();
}
}
}
return true;
}
FXSTUDIOCORE_API int DestroyInstance()
{
g_pApp->OnClose();
Logger::Destroy();
return 0;
}
FXSTUDIOCORE_API void ResizeWnd(int screenWidth, int screenHeight)
{
g_pApp->OnResize(screenWidth, screenHeight);
}
FXSTUDIOCORE_API void WndProc(int *hWndPtrAddress, int uMsg, int* wParam, int* lParam)
{
HWND hWnd = (HWND)hWndPtrAddress;
switch (uMsg)
{
case WM_CLOSE:
g_pApp->OnClose();
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_CHAR:
case WM_MOUSEMOVE:
case WM_MOUSEWHEEL:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
{
if (g_pApp->GetGameLogic() != nullptr)
{
AppMsg msg;
msg.m_hWnd = hWnd;
msg.m_uMsg = uMsg;
msg.m_wParam = WPARAM(wParam);
msg.m_lParam = LPARAM(lParam);
g_pApp->OnDispatchMsg(msg);
}
break;
}
}
}
FXSTUDIOCORE_API void RenderFrame()
{
g_pApp->OnRenderFrame();
}
FXSTUDIOCORE_API bool IsGameRunning()
{
return true;
}
FXSTUDIOCORE_API void OpenProject(BSTR lFileName)
{
std::string project = Utility::WS2S(std::wstring(lFileName, SysStringLen(lFileName)));
FXStudioLogic* pEditorLogic = dynamic_cast<FXStudioLogic*>(g_pApp->GetGameLogic());
if (pEditorLogic != nullptr)
{
g_pApp->GetGameConfig().m_Project = project;
pEditorLogic->VChangeState(BGS_LoadingGameEnvironment);
}
}
FXSTUDIOCORE_API void CreateNewProject(BSTR lFileName)
{
std::string project = Utility::WS2S(std::wstring(lFileName, SysStringLen(lFileName)));
FXStudioLogic* pEditorLogic = dynamic_cast<FXStudioLogic*>(g_pApp->GetGameLogic());
if (pEditorLogic != nullptr)
{
pEditorLogic->VCreateNewProject(project);
}
}
FXSTUDIOCORE_API int PickActor(int* hWndPterAddress)
{
HWND hWnd = (HWND)hWndPterAddress;
POINT cursor;
::GetCursorPos(&cursor);
::ScreenToClient(hWnd, &cursor);
return -1;
}
FXSTUDIOCORE_API unsigned int AddActor(BSTR actorResource)
{
std::string actorXml = Utility::WS2S(std::wstring(actorResource, SysStringLen(actorResource)));
StrongActorPtr pActor = g_pApp->GetGameLogic()->VCreateActor(actorXml);
if (!pActor)
return INVALID_ACTOR_ID;
return pActor->GetActorId();
}
FXSTUDIOCORE_API bool ModifyActor(BSTR modificationXml)
{
return true;
}
FXSTUDIOCORE_API bool RemoveActor(unsigned int actorId)
{
g_pApp->GetGameLogic()->VDestroyActor(actorId);
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 1999 Lars Knoll ([email protected])
* (C) 2004-2005 Allan Sandfeld Jensen ([email protected])
* Copyright (C) 2006, 2007 Nicholas Shanks ([email protected])
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alexey Proskuryakov <[email protected]>
* Copyright (C) 2007, 2008 Eric Seidel <[email protected]>
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/dom/VisitedLinkState.h"
#include "core/HTMLNames.h"
#include "core/XLinkNames.h"
#include "core/dom/ElementTraversal.h"
#include "core/html/HTMLAnchorElement.h"
#include "public/platform/Platform.h"
namespace blink {
static inline const AtomicString& linkAttribute(const Element& element)
{
ASSERT(element.isLink());
if (element.isHTMLElement())
return element.fastGetAttribute(HTMLNames::hrefAttr);
ASSERT(element.isSVGElement());
return element.getAttribute(XLinkNames::hrefAttr);
}
static inline LinkHash linkHashForElement(const Element& element, const AtomicString& attribute = AtomicString())
{
ASSERT(attribute.isNull() || linkAttribute(element) == attribute);
if (isHTMLAnchorElement(element))
return toHTMLAnchorElement(element).visitedLinkHash();
return visitedLinkHash(element.document().baseURL(), attribute.isNull() ? linkAttribute(element) : attribute);
}
VisitedLinkState::VisitedLinkState(const Document& document)
: m_document(document)
{
}
void VisitedLinkState::invalidateStyleForAllLinks()
{
if (m_linksCheckedForVisitedState.isEmpty())
return;
for (Element* element = ElementTraversal::firstWithin(document()); element; element = ElementTraversal::next(*element)) {
if (element->isLink())
element->setNeedsStyleRecalc(SubtreeStyleChange);
}
}
void VisitedLinkState::invalidateStyleForLink(LinkHash linkHash)
{
if (!m_linksCheckedForVisitedState.contains(linkHash))
return;
for (Element* element = ElementTraversal::firstWithin(document()); element; element = ElementTraversal::next(*element)) {
if (element->isLink() && linkHashForElement(*element) == linkHash)
element->setNeedsStyleRecalc(SubtreeStyleChange);
}
}
EInsideLink VisitedLinkState::determineLinkStateSlowCase(const Element& element)
{
ASSERT(element.isLink());
ASSERT(document().isActive());
ASSERT(document() == element.document());
const AtomicString& attribute = linkAttribute(element);
if (attribute.isNull())
return NotInsideLink; // This can happen for <img usemap>
// An empty attribute refers to the document itself which is always
// visited. It is useful to check this explicitly so that visited
// links can be tested in platform independent manner, without
// explicit support in the test harness.
if (attribute.isEmpty())
return InsideVisitedLink;
if (LinkHash hash = linkHashForElement(element, attribute)) {
m_linksCheckedForVisitedState.add(hash);
if (Platform::current()->isLinkVisited(hash))
return InsideVisitedLink;
}
return InsideUnvisitedLink;
}
void VisitedLinkState::trace(Visitor* visitor)
{
visitor->trace(m_document);
}
} // namespace blink
<commit_msg>Use NodeTraversal instead of ElementTraversal in VisitedLinkState<commit_after>/*
* Copyright (C) 1999 Lars Knoll ([email protected])
* (C) 2004-2005 Allan Sandfeld Jensen ([email protected])
* Copyright (C) 2006, 2007 Nicholas Shanks ([email protected])
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alexey Proskuryakov <[email protected]>
* Copyright (C) 2007, 2008 Eric Seidel <[email protected]>
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/dom/VisitedLinkState.h"
#include "core/HTMLNames.h"
#include "core/XLinkNames.h"
#include "core/dom/ElementTraversal.h"
#include "core/html/HTMLAnchorElement.h"
#include "public/platform/Platform.h"
namespace blink {
static inline const AtomicString& linkAttribute(const Element& element)
{
ASSERT(element.isLink());
if (element.isHTMLElement())
return element.fastGetAttribute(HTMLNames::hrefAttr);
ASSERT(element.isSVGElement());
return element.getAttribute(XLinkNames::hrefAttr);
}
static inline LinkHash linkHashForElement(const Element& element, const AtomicString& attribute = AtomicString())
{
ASSERT(attribute.isNull() || linkAttribute(element) == attribute);
if (isHTMLAnchorElement(element))
return toHTMLAnchorElement(element).visitedLinkHash();
return visitedLinkHash(element.document().baseURL(), attribute.isNull() ? linkAttribute(element) : attribute);
}
VisitedLinkState::VisitedLinkState(const Document& document)
: m_document(document)
{
}
void VisitedLinkState::invalidateStyleForAllLinks()
{
if (m_linksCheckedForVisitedState.isEmpty())
return;
for (Node* node = document().firstChild(); node; node = NodeTraversal::next(*node)) {
if (node->isLink())
node->setNeedsStyleRecalc(SubtreeStyleChange);
}
}
void VisitedLinkState::invalidateStyleForLink(LinkHash linkHash)
{
if (!m_linksCheckedForVisitedState.contains(linkHash))
return;
for (Node* node = document().firstChild(); node; node = NodeTraversal::next(*node)) {
if (node->isLink() && linkHashForElement(toElement(*node)) == linkHash)
node->setNeedsStyleRecalc(SubtreeStyleChange);
}
}
EInsideLink VisitedLinkState::determineLinkStateSlowCase(const Element& element)
{
ASSERT(element.isLink());
ASSERT(document().isActive());
ASSERT(document() == element.document());
const AtomicString& attribute = linkAttribute(element);
if (attribute.isNull())
return NotInsideLink; // This can happen for <img usemap>
// An empty attribute refers to the document itself which is always
// visited. It is useful to check this explicitly so that visited
// links can be tested in platform independent manner, without
// explicit support in the test harness.
if (attribute.isEmpty())
return InsideVisitedLink;
if (LinkHash hash = linkHashForElement(element, attribute)) {
m_linksCheckedForVisitedState.add(hash);
if (Platform::current()->isLinkVisited(hash))
return InsideVisitedLink;
}
return InsideUnvisitedLink;
}
void VisitedLinkState::trace(Visitor* visitor)
{
visitor->trace(m_document);
}
} // namespace blink
<|endoftext|>
|
<commit_before>// JSON condenser exmaple
// This example parses JSON from stdin with validation,
// and re-output the JSON content to stdout with all string capitalized, and without whitespace.
#include "rapidjson/reader.h"
#include "rapidjson/writer.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/error/en.h"
#include <vector>
#include <cctype>
using namespace rapidjson;
template<typename OutputHandler>
struct CapitalizeFilter {
CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {}
bool Null() { return out_.Null(); }
bool Bool(bool b) { return out_.Bool(b); }
bool Int(int i) { return out_.Int(i); }
bool Uint(unsigned u) { return out_.Uint(u); }
bool Int64(int64_t i) { return out_.Int64(i); }
bool Uint64(uint64_t u) { return out_.Uint64(u); }
bool Double(double d) { return out_.Double(d); }
bool String(const char* str, SizeType length, bool) {
buffer_.clear();
for (SizeType i = 0; i < length; i++)
buffer_.push_back(std::toupper(str[i]));
return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
}
bool StartObject() { return out_.StartObject(); }
bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
bool StartArray() { return out_.StartArray(); }
bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
OutputHandler& out_;
std::vector<char> buffer_;
private:
CapitalizeFilter(const CapitalizeFilter&);
CapitalizeFilter& operator=(const CapitalizeFilter&);
};
int main(int, char*[]) {
// Prepare JSON reader and input stream.
Reader reader;
char readBuffer[65536];
FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
// Prepare JSON writer and output stream.
char writeBuffer[65536];
FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
// JSON reader parse from the input stream and let writer generate the output.
CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
if (!reader.Parse(is, filter)) {
fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
return 1;
}
return 0;
}
<commit_msg>add `Key()->String()` forwarding to the `capitalize` example<commit_after>// JSON condenser exmaple
// This example parses JSON from stdin with validation,
// and re-output the JSON content to stdout with all string capitalized, and without whitespace.
#include "rapidjson/reader.h"
#include "rapidjson/writer.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/filewritestream.h"
#include "rapidjson/error/en.h"
#include <vector>
#include <cctype>
using namespace rapidjson;
template<typename OutputHandler>
struct CapitalizeFilter {
CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {}
bool Null() { return out_.Null(); }
bool Bool(bool b) { return out_.Bool(b); }
bool Int(int i) { return out_.Int(i); }
bool Uint(unsigned u) { return out_.Uint(u); }
bool Int64(int64_t i) { return out_.Int64(i); }
bool Uint64(uint64_t u) { return out_.Uint64(u); }
bool Double(double d) { return out_.Double(d); }
bool String(const char* str, SizeType length, bool) {
buffer_.clear();
for (SizeType i = 0; i < length; i++)
buffer_.push_back(std::toupper(str[i]));
return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
}
bool StartObject() { return out_.StartObject(); }
bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); }
bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); }
bool StartArray() { return out_.StartArray(); }
bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); }
OutputHandler& out_;
std::vector<char> buffer_;
private:
CapitalizeFilter(const CapitalizeFilter&);
CapitalizeFilter& operator=(const CapitalizeFilter&);
};
int main(int, char*[]) {
// Prepare JSON reader and input stream.
Reader reader;
char readBuffer[65536];
FileReadStream is(stdin, readBuffer, sizeof(readBuffer));
// Prepare JSON writer and output stream.
char writeBuffer[65536];
FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
// JSON reader parse from the input stream and let writer generate the output.
CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
if (!reader.Parse(is, filter)) {
fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/webmidi/MIDIInput.h"
#include "modules/webmidi/MIDIMessageEvent.h"
namespace WebCore {
PassRefPtr<MIDIInput> MIDIInput::create(ScriptExecutionContext* context, const String& id, const String& manufacturer, const String& name, const String& version)
{
return adoptRef(new MIDIInput(context, id, manufacturer, name, version));
}
MIDIInput::MIDIInput(ScriptExecutionContext* context, const String& id, const String& manufacturer, const String& name, const String& version)
: MIDIPort(context, id, manufacturer, name, MIDIPortTypeInput, version)
{
ScriptWrappable::init(this);
}
void MIDIInput::didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp)
{
ASSERT(isMainThread());
RefPtr<Uint8Array> array = Uint8Array::create(length);
array->setRange(data, length, 0);
dispatchEvent(MIDIMessageEvent::create(timeStamp, array));
}
} // namespace WebCore
<commit_msg>Dispatch separate MIDIMessageEvents for multiple messages in the received data buffer.<commit_after>/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/webmidi/MIDIInput.h"
#include "modules/webmidi/MIDIMessageEvent.h"
namespace WebCore {
PassRefPtr<MIDIInput> MIDIInput::create(ScriptExecutionContext* context, const String& id, const String& manufacturer, const String& name, const String& version)
{
return adoptRef(new MIDIInput(context, id, manufacturer, name, version));
}
MIDIInput::MIDIInput(ScriptExecutionContext* context, const String& id, const String& manufacturer, const String& name, const String& version)
: MIDIPort(context, id, manufacturer, name, MIDIPortTypeInput, version)
{
ScriptWrappable::init(this);
}
void MIDIInput::didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp)
{
ASSERT(isMainThread());
// The received MIDI data may contain one or more messages.
// The Web MIDI API requires that a separate event be dispatched for each message,
// so we walk through the data and dispatch one at a time.
size_t i = 0;
while (i < length) {
unsigned char status = data[i];
unsigned char strippedStatus = status & 0xf0;
// FIXME: support System Exclusive.
if (strippedStatus >= 0xf0)
break;
// All non System Exclusive messages have a total size of 3 except for Program Change and Channel Pressure.
size_t totalMessageSize = (strippedStatus == 0xc0 || strippedStatus == 0xd0) ? 2 : 3;
if (i + totalMessageSize <= length) {
RefPtr<Uint8Array> array = Uint8Array::create(totalMessageSize);
array->setRange(data + i, totalMessageSize, 0);
dispatchEvent(MIDIMessageEvent::create(timeStamp, array));
}
i += totalMessageSize;
}
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>//
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//
#include "stdafx.h"
#include "Render/Renderer.h"
#include "Render/DX12/RendererDX12.h"
namespace Kioto::Renderer
{
RendererDX12 renderer; // [a_vorontsov] Not too cross-api for now.
void Init(eRenderApi api, uint16 width, uint16 height)
{
if (api == eRenderApi::DirectX12)
renderer.Init(width, height);
}
void Shutdown()
{
renderer.Shutdown();
}
void Resize(uint16 width, uint16 height, bool minimized)
{
renderer.Resize(width, height);
}
void ChangeFullscreenMode(bool fullScreen)
{
}
void Update(float32 dt) // [a_vorontsov] TODO: set frame command buffers here.
{
}
void Present()
{
renderer.Present();
}
}<commit_msg>Fix access violations.<commit_after>//
// Copyright (C) Alexandr Vorontsov. 2017
// Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
//
#include "stdafx.h"
#include "Render/Renderer.h"
#include "Render/DX12/RendererDX12.h"
namespace Kioto::Renderer
{
RendererDX12* renderer = new RendererDX12(); // [a_vorontsov] Not too cross-api for now.
void Init(eRenderApi api, uint16 width, uint16 height)
{
if (api == eRenderApi::DirectX12)
renderer->Init(width, height);
}
void Shutdown()
{
renderer->Shutdown();
}
void Resize(uint16 width, uint16 height, bool minimized)
{
renderer->Resize(width, height);
}
void ChangeFullscreenMode(bool fullScreen)
{
}
void Update(float32 dt) // [a_vorontsov] TODO: set frame command buffers here.
{
}
void Present()
{
renderer->Present();
}
}<|endoftext|>
|
<commit_before>#include <iostream>
#include <algorithm>
#include <exception>
#include <vector>
#include <memory>
#include "csimplesocket/ActiveSocket.h"
#include "json.hpp"
#include "core/api.h"
#include "strategy.h"
using json = nlohmann::json;
const int PACKET_SIZE = 8096;
namespace
{
template<typename JSON>
void fill_passenger(Passenger &passenger, const JSON &jpassenger)
{
passenger.id = jpassenger["id"];
passenger.x = jpassenger["x"];
passenger.y = jpassenger["y"];
passenger.weight = jpassenger["weight"];
passenger.from_floor = jpassenger["from_floor"];
passenger.dest_floor = jpassenger["dest_floor"];
passenger.time_to_away = jpassenger["time_to_away"];
passenger.type = jpassenger["type"];
passenger.floor = jpassenger["floor"];
passenger.elevator = jpassenger["elevator"].is_null() ? -1 : jpassenger["elevator"].is_null();
passenger.state = jpassenger["state"];
}
template<typename JSON>
void fill_elevator(Elevator &elevator, const JSON &jelevator)
{
elevator.id = jelevator["id"];
elevator.y = jelevator["y"];
elevator.speed = jelevator["speed"];
elevator.time_on_floor = jelevator["time_on_floor"];
elevator.next_floor = jelevator["next_floor"];
elevator.type = jelevator["type"];
elevator.floor = jelevator["floor"];
elevator.state = jelevator["state"];
for (auto && jpassenger : jelevator["passengers"])
{
elevator.passengers.emplace_back();
::fill_passenger(*elevator.passengers.rbegin(), jpassenger);
}
}
}
class Client
{
public:
Client(const std::string &host, int port, const std::string &solution_id)
: host(host), port(port), solution_id(solution_id)
{
client.Initialize();
client.DisableNagleAlgoritm();
}
~Client()
{
client.Close();
}
bool open()
{
bool result = client.Open(host.c_str(), port);
if (result)
{
json obj = {{"solution_id", solution_id}};
std::string message = obj.dump() + "\n";
send(message.c_str(), message.length());
}
return result;
}
int run()
{
std::string line;
while(1)
{
int numBytes = client.Receive(PACKET_SIZE);
if (numBytes <= 0)
{
std::cout << "Input closed" << std::endl;
if (!line.empty())
{
if (!doCommand(line))
return 0;
}
return -2;
}
uint8 * data = client.GetData();
uint8 * data_end = data + numBytes;
uint8 * endOfLine;
while ((endOfLine = std::find(data, data + numBytes, '\n')) < data_end)
{
line.append(data, endOfLine);
if (!doCommand(line))
return 0;
line.clear();
data = endOfLine + 1;
}
line.append(data, data_end);
}
return 0;
}
bool doCommand(const std::string &line)
{
try
{
auto cmd = json::parse(line);
if (cmd.count("message") && cmd["message"] == std::string("down"))
{
std::cout << "Down" << std::endl;
return false;
}
if (!started)
{
if (cmd["message"] != std::string("beginning"))
{
std::cerr << "Unknown command " << line << std::endl;
exit(-3);
}
started = true;
strategy.reset(new Strategy());
return true;
}
std::vector<Elevator> my_elevators;
std::vector<Elevator> enemy_elevators;
std::vector<Passenger> my_passengers;
std::vector<Passenger> enemy_passengers;
for (auto && jelevator : cmd["my_elevators"])
{
my_elevators.emplace_back();
::fill_elevator(*my_elevators.rbegin(), jelevator);
}
for (auto && jelevator : cmd["enemy_elevators"])
{
enemy_elevators.emplace_back();
::fill_elevator(*enemy_elevators.rbegin(), jelevator);
}
for (auto && jpassenger : cmd["my_passengers"])
{
my_passengers.emplace_back();
::fill_passenger(*my_passengers.rbegin(), jpassenger);
}
for (auto && jpassenger : cmd["enemy_passengers"])
{
enemy_passengers.emplace_back();
::fill_passenger(*enemy_passengers.rbegin(), jpassenger);
}
strategy->logs.clear();
strategy->on_tick(my_elevators, my_passengers, enemy_elevators, enemy_passengers);
messages = json::array();
for (Elevator &elevator : my_elevators)
{
go_to_floor_commands(elevator);
}
for (Passenger &passenger : my_passengers)
{
set_elevator_to_passenger_commands(passenger);
}
for (Passenger &passenger : enemy_passengers)
{
set_elevator_to_passenger_commands(passenger);
}
log_commands(*strategy);
std::string message = messages.dump() + "\n";
send(message.c_str(), message.length());
return true;
}
catch (...)
{
std::cerr << "Error while processing command " << line << std::endl;
throw;
}
return false;
}
private:
CActiveSocket client;
std::string host;
int port;
std::string solution_id;
bool started = false;
std::unique_ptr<Strategy> strategy;
json messages;
void go_to_floor_commands(Elevator &elevator)
{
for (int floor : elevator.go_to_floor_floors)
{
json obj = {
{"command", "go_to_floor"},
{ "args", {
{"elevator_id", elevator.id},
{"floor", floor}
}
}
};
messages.push_back(obj);
}
}
void set_elevator_to_passenger_commands(Passenger &passenger)
{
for (int set_elevator_id : passenger.set_elevator_ids)
{
json obj = {
{"command", "set_elevator_to_passenger"},
{ "args", {
{"passenger_id", passenger.id},
{"elevator_id", set_elevator_id}
}
}
};
messages.push_back(obj);
}
}
void log_commands(BaseStrategy &base_strategy)
{
for (std::pair<bool, std::stringstream> &log : base_strategy.logs)
{
json obj = {
{"command", log.first ? "exception" : "log"},
{ "args", {
{"text", log.second.str()}
}
}
};
messages.push_back(obj);
}
}
void send(const char *bytes, size_t byteCount) {
unsigned int offset = 0;
int sentByteCount;
while (offset < byteCount && (sentByteCount = client.Send(reinterpret_cast<const uint8*>(bytes + offset), byteCount - offset)) > 0) {
offset += sentByteCount;
}
if (offset != byteCount) {
exit(10013);
}
}
};
int main()
{
std::string host = "127.0.0.1";
std::string solution_id = "-1";
int port = 8000;
const char* env_value;
if ((env_value = std::getenv("WORLD_NAME")))
{
host = env_value;
}
if ((env_value = std::getenv("SOLUTION_ID")))
{
solution_id = env_value;
}
Client client(host, port, solution_id);
if (!client.open())
{
std::cerr << "Error opening connection" << std::endl;
return -1;
}
return client.run();
}
<commit_msg>passenger floor fix<commit_after>#include <iostream>
#include <algorithm>
#include <exception>
#include <vector>
#include <memory>
#include "csimplesocket/ActiveSocket.h"
#include "json.hpp"
#include "core/api.h"
#include "strategy.h"
using json = nlohmann::json;
const int PACKET_SIZE = 8096;
namespace
{
template<typename JSON>
void fill_passenger(Passenger &passenger, const JSON &jpassenger)
{
passenger.id = jpassenger["id"];
passenger.x = jpassenger["x"];
passenger.y = jpassenger["y"];
passenger.weight = jpassenger["weight"];
passenger.from_floor = jpassenger["from_floor"];
passenger.dest_floor = jpassenger["dest_floor"];
passenger.time_to_away = jpassenger["time_to_away"];
passenger.type = jpassenger["type"];
passenger.floor = jpassenger["floor"];
if (jpassenger["elevator"].is_null())
passenger.elevator = - 1;
else
passenger.elevator = jpassenger["elevator"];
passenger.state = jpassenger["state"];
}
template<typename JSON>
void fill_elevator(Elevator &elevator, const JSON &jelevator)
{
elevator.id = jelevator["id"];
elevator.y = jelevator["y"];
elevator.speed = jelevator["speed"];
elevator.time_on_floor = jelevator["time_on_floor"];
elevator.next_floor = jelevator["next_floor"];
elevator.type = jelevator["type"];
elevator.floor = jelevator["floor"];
elevator.state = jelevator["state"];
for (auto && jpassenger : jelevator["passengers"])
{
elevator.passengers.emplace_back();
::fill_passenger(*elevator.passengers.rbegin(), jpassenger);
}
}
}
class Client
{
public:
Client(const std::string &host, int port, const std::string &solution_id)
: host(host), port(port), solution_id(solution_id)
{
client.Initialize();
client.DisableNagleAlgoritm();
}
~Client()
{
client.Close();
}
bool open()
{
bool result = client.Open(host.c_str(), port);
if (result)
{
json obj = {{"solution_id", solution_id}};
std::string message = obj.dump() + "\n";
send(message.c_str(), message.length());
}
return result;
}
int run()
{
std::string line;
while(1)
{
int numBytes = client.Receive(PACKET_SIZE);
if (numBytes <= 0)
{
std::cout << "Input closed" << std::endl;
if (!line.empty())
{
if (!doCommand(line))
return 0;
}
return -2;
}
uint8 * data = client.GetData();
uint8 * data_end = data + numBytes;
uint8 * endOfLine;
while ((endOfLine = std::find(data, data + numBytes, '\n')) < data_end)
{
line.append(data, endOfLine);
if (!doCommand(line))
return 0;
line.clear();
data = endOfLine + 1;
}
line.append(data, data_end);
}
return 0;
}
bool doCommand(const std::string &line)
{
try
{
auto cmd = json::parse(line);
if (cmd.count("message") && cmd["message"] == std::string("down"))
{
std::cout << "Down" << std::endl;
return false;
}
if (!started)
{
if (cmd["message"] != std::string("beginning"))
{
std::cerr << "Unknown command " << line << std::endl;
exit(-3);
}
started = true;
strategy.reset(new Strategy());
return true;
}
std::vector<Elevator> my_elevators;
std::vector<Elevator> enemy_elevators;
std::vector<Passenger> my_passengers;
std::vector<Passenger> enemy_passengers;
for (auto && jelevator : cmd["my_elevators"])
{
my_elevators.emplace_back();
::fill_elevator(*my_elevators.rbegin(), jelevator);
}
for (auto && jelevator : cmd["enemy_elevators"])
{
enemy_elevators.emplace_back();
::fill_elevator(*enemy_elevators.rbegin(), jelevator);
}
for (auto && jpassenger : cmd["my_passengers"])
{
my_passengers.emplace_back();
::fill_passenger(*my_passengers.rbegin(), jpassenger);
}
for (auto && jpassenger : cmd["enemy_passengers"])
{
enemy_passengers.emplace_back();
::fill_passenger(*enemy_passengers.rbegin(), jpassenger);
}
strategy->logs.clear();
strategy->on_tick(my_elevators, my_passengers, enemy_elevators, enemy_passengers);
messages = json::array();
for (Elevator &elevator : my_elevators)
{
go_to_floor_commands(elevator);
}
for (Passenger &passenger : my_passengers)
{
set_elevator_to_passenger_commands(passenger);
}
for (Passenger &passenger : enemy_passengers)
{
set_elevator_to_passenger_commands(passenger);
}
log_commands(*strategy);
std::string message = messages.dump() + "\n";
send(message.c_str(), message.length());
return true;
}
catch (...)
{
std::cerr << "Error while processing command " << line << std::endl;
throw;
}
return false;
}
private:
CActiveSocket client;
std::string host;
int port;
std::string solution_id;
bool started = false;
std::unique_ptr<Strategy> strategy;
json messages;
void go_to_floor_commands(Elevator &elevator)
{
for (int floor : elevator.go_to_floor_floors)
{
json obj = {
{"command", "go_to_floor"},
{ "args", {
{"elevator_id", elevator.id},
{"floor", floor}
}
}
};
messages.push_back(obj);
}
}
void set_elevator_to_passenger_commands(Passenger &passenger)
{
for (int set_elevator_id : passenger.set_elevator_ids)
{
json obj = {
{"command", "set_elevator_to_passenger"},
{ "args", {
{"passenger_id", passenger.id},
{"elevator_id", set_elevator_id}
}
}
};
messages.push_back(obj);
}
}
void log_commands(BaseStrategy &base_strategy)
{
for (std::pair<bool, std::stringstream> &log : base_strategy.logs)
{
json obj = {
{"command", log.first ? "exception" : "log"},
{ "args", {
{"text", log.second.str()}
}
}
};
messages.push_back(obj);
}
}
void send(const char *bytes, size_t byteCount) {
unsigned int offset = 0;
int sentByteCount;
while (offset < byteCount && (sentByteCount = client.Send(reinterpret_cast<const uint8*>(bytes + offset), byteCount - offset)) > 0) {
offset += sentByteCount;
}
if (offset != byteCount) {
exit(10013);
}
}
};
int main()
{
std::string host = "127.0.0.1";
std::string solution_id = "-1";
int port = 8000;
const char* env_value;
if ((env_value = std::getenv("WORLD_NAME")))
{
host = env_value;
}
if ((env_value = std::getenv("SOLUTION_ID")))
{
solution_id = env_value;
}
Client client(host, port, solution_id);
if (!client.open())
{
std::cerr << "Error opening connection" << std::endl;
return -1;
}
return client.run();
}
<|endoftext|>
|
<commit_before>#include "AnalysisSolver.h"
#include <sofa/core/ObjectFactory.h>
#include <Eigen/SVD>
#include <Eigen/Eigenvalues>
namespace sofa {
namespace component {
namespace linearsolver {
SOFA_DECL_CLASS(AnalysisSolver)
int AnalysisSolverClass = core::RegisterObject("Analysis solver: runs other KKTSolvers successively on a given problem and performs extra analysis on KKT system").add< AnalysisSolver >();
AnalysisSolver::AnalysisSolver()
: condest(initData(&condest, false, "condest", "compute condition number with svd"))
, eigenvaluesign(initData(&eigenvaluesign, false, "eigenvaluesign", "computing the sign of the eigenvalues (of the implicit matrix H)"))
, dump_qp(initData(&dump_qp, "dump_qp", "dump qp to file if non-empty"))
{}
void AnalysisSolver::init() {
solvers.clear();
this->getContext()->get<KKTSolver>( &solvers, core::objectmodel::BaseContext::Local );
if( solvers.size() < 2 ) {
std::cerr << "warning: no other kkt solvers found" << std::endl;
} else {
std::cout << "AnalysisSolver: dynamics/correction will use "
<< solvers.back()->getName()
<< std::endl;
}
}
void AnalysisSolver::factor(const system_type& system) {
// start at 1 since 0 is current solver
for( unsigned i = 1, n = solvers.size() ; i < n; ++i ) {
solvers[i]->factor(system);
}
typedef system_type::dmat dmat;
if( condest.getValue() ) {
dmat kkt;
kkt.setZero(system.size(), system.size());
kkt <<
dmat(system.H), dmat(-system.J.transpose()),
dmat(-system.J), dmat(-system.C);
system_type::vec eigen = kkt.jacobiSvd().singularValues();
real min = eigen.tail<1>()(0);
real max = eigen(0);
if( min < std::numeric_limits<real>::epsilon() ) std::cout << "AnalysisSolver: singular system"<<std::endl;
else
{
const real cond = max/min;
std::cout << "condition number: " << cond << "("<<max<<"/"<<min<<")"<<std::endl;
std::cout << "required precision: "<<log(cond)<<" bits"<<std::endl;
}
eigen = dmat(system.H).jacobiSvd().singularValues();
min = eigen.tail<1>()(0);
max = eigen(0);
if( min < std::numeric_limits<real>::epsilon() ) std::cout << "AnalysisSolver: singular implicit system"<<std::endl;
else
{
const real cond = max/min;
std::cout << "condition number implicit system: " << cond << "("<<max<<"/"<<min<<")"<<std::endl;
std::cout << "required precision implicit system: "<<log(cond)<<" bits"<<std::endl;
}
}
if( eigenvaluesign.getValue() ) {
Eigen::EigenSolver<dmat> es( dmat(system.H) );
// Eigen::MatrixXcd D = es.eigenvalues().asDiagonal();
unsigned positive = 0, negative = 0;
for( dmat::Index i =0 ; i< es.eigenvalues().rows() ; ++i )
if( es.eigenvalues()[i].real() < 0 ) negative++;
else positive++;
std::cout << "eigenvalues H: neg="<<negative<<" pos="<<positive<<std::endl;
if( negative )
{
getContext()->getRootContext()->setAnimate(false);
std::cerr<<es.eigenvalues().array().abs().minCoeff()<<std::endl;
std::cerr<<" $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n";
}
}
// TODO add more as needed
}
static void write_qp(std::ofstream& out,
const AssembledSystem& sys,
const AssembledSystem::vec& rhs) {
const char endl = '\n';
out << sys.m << ' ' << sys.n << endl;
out << sys.H << endl;
out << -rhs.head(sys.m).transpose() << endl;
out << sys.P << endl;
if( sys.n ) {
out << sys.J << endl;
out << rhs.tail(sys.n).transpose() << endl;
// TODO unilateral mask !
}
}
// solution is that of the first solver
void AnalysisSolver::correct(vec& res,
const system_type& sys,
const vec& rhs,
real damping) const {
assert( solvers.size() > 1 );
solvers.back()->correct(res, sys, rhs, damping);
if(!dump_qp.getValue().empty() ) {
std::ofstream out(dump_qp.getValue() + ".correction" );
write_qp(out, sys, rhs);
}
}
// solution is that of the last solver
void AnalysisSolver::solve(vec& res,
const system_type& sys,
const vec& rhs) const {
vec backup = res; // backup initial solution
// start at 1 since 0 is current solver
for( unsigned i = 1, n = solvers.size(); i < n; ++i ) {
res = backup;
solvers[i]->solve(res, sys, rhs);
}
if(!dump_qp.getValue().empty() ) {
std::ofstream out(dump_qp.getValue() + ".dynamics" );
write_qp(out, sys, rhs);
}
}
}
}
}
<commit_msg>Compliant: fixed compilation (whoopsie)<commit_after>#include "AnalysisSolver.h"
#include <sofa/core/ObjectFactory.h>
#include <Eigen/SVD>
#include <Eigen/Eigenvalues>
namespace sofa {
namespace component {
namespace linearsolver {
SOFA_DECL_CLASS(AnalysisSolver)
int AnalysisSolverClass = core::RegisterObject("Analysis solver: runs other KKTSolvers successively on a given problem and performs extra analysis on KKT system").add< AnalysisSolver >();
AnalysisSolver::AnalysisSolver()
: condest(initData(&condest, false, "condest", "compute condition number with svd"))
, eigenvaluesign(initData(&eigenvaluesign, false, "eigenvaluesign", "computing the sign of the eigenvalues (of the implicit matrix H)"))
, dump_qp(initData(&dump_qp, "dump_qp", "dump qp to file if non-empty"))
{}
void AnalysisSolver::init() {
solvers.clear();
this->getContext()->get<KKTSolver>( &solvers, core::objectmodel::BaseContext::Local );
if( solvers.size() < 2 ) {
std::cerr << "warning: no other kkt solvers found" << std::endl;
} else {
std::cout << "AnalysisSolver: dynamics/correction will use "
<< solvers.back()->getName()
<< std::endl;
}
}
void AnalysisSolver::factor(const system_type& system) {
// start at 1 since 0 is current solver
for( unsigned i = 1, n = solvers.size() ; i < n; ++i ) {
solvers[i]->factor(system);
}
typedef system_type::dmat dmat;
if( condest.getValue() ) {
dmat kkt;
kkt.setZero(system.size(), system.size());
kkt <<
dmat(system.H), dmat(-system.J.transpose()),
dmat(-system.J), dmat(-system.C);
system_type::vec eigen = kkt.jacobiSvd().singularValues();
real min = eigen.tail<1>()(0);
real max = eigen(0);
if( min < std::numeric_limits<real>::epsilon() ) std::cout << "AnalysisSolver: singular system"<<std::endl;
else
{
const real cond = max/min;
std::cout << "condition number: " << cond << "("<<max<<"/"<<min<<")"<<std::endl;
std::cout << "required precision: "<<log(cond)<<" bits"<<std::endl;
}
eigen = dmat(system.H).jacobiSvd().singularValues();
min = eigen.tail<1>()(0);
max = eigen(0);
if( min < std::numeric_limits<real>::epsilon() ) std::cout << "AnalysisSolver: singular implicit system"<<std::endl;
else
{
const real cond = max/min;
std::cout << "condition number implicit system: " << cond << "("<<max<<"/"<<min<<")"<<std::endl;
std::cout << "required precision implicit system: "<<log(cond)<<" bits"<<std::endl;
}
}
if( eigenvaluesign.getValue() ) {
Eigen::EigenSolver<dmat> es( dmat(system.H) );
// Eigen::MatrixXcd D = es.eigenvalues().asDiagonal();
unsigned positive = 0, negative = 0;
for( dmat::Index i =0 ; i< es.eigenvalues().rows() ; ++i )
if( es.eigenvalues()[i].real() < 0 ) negative++;
else positive++;
std::cout << "eigenvalues H: neg="<<negative<<" pos="<<positive<<std::endl;
if( negative )
{
getContext()->getRootContext()->setAnimate(false);
std::cerr<<es.eigenvalues().array().abs().minCoeff()<<std::endl;
std::cerr<<" $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n";
}
}
// TODO add more as needed
}
static void write_qp(std::ofstream& out,
const AssembledSystem& sys,
const AssembledSystem::vec& rhs) {
const char endl = '\n';
out << sys.m << ' ' << sys.n << endl;
out << sys.H << endl;
out << -rhs.head(sys.m).transpose() << endl;
out << sys.P << endl;
if( sys.n ) {
out << sys.J << endl;
out << rhs.tail(sys.n).transpose() << endl;
// TODO unilateral mask !
}
}
// solution is that of the first solver
void AnalysisSolver::correct(vec& res,
const system_type& sys,
const vec& rhs,
real damping) const {
assert( solvers.size() > 1 );
solvers.back()->correct(res, sys, rhs, damping);
if(!dump_qp.getValue().empty() ) {
const std::string filename = dump_qp.getValue() + ".correction";
std::ofstream out(filename.c_str());
write_qp(out, sys, rhs);
}
}
// solution is that of the last solver
void AnalysisSolver::solve(vec& res,
const system_type& sys,
const vec& rhs) const {
vec backup = res; // backup initial solution
// start at 1 since 0 is current solver
for( unsigned i = 1, n = solvers.size(); i < n; ++i ) {
res = backup;
solvers[i]->solve(res, sys, rhs);
}
if(!dump_qp.getValue().empty() ) {
const std::string filename = dump_qp.getValue() + ".correction";
std::ofstream out(filename.c_str());
write_qp(out, sys, rhs);
}
}
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Wait for the history backend to load, which makes AutocompleteBrowserTest.Autocomplete not flaky.<commit_after><|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.